让我们想想游戏的流程是什么:陨石随机产生,从上方落下,玩家控制飞机躲避并发射子弹击中陨石,击中陨石加分并且显示在屏幕上,飞机撞到陨石游戏结束,按R键重新开始。
本篇脚本实现陨石随机产生、加分、游戏结束判断、按R键重新开始这四个功能。
这里用到了通过协程实现陨石不断随机产生,yield语句使语句的执行有间隔时间段。
使用SceneManager.LoadScene函数实现游戏重启。
加分函数和游戏结束函数都是在碰撞脚本中被调用
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine;
public class GameController : MonoBehaviour {
public Vector3 spawnValue;
public GameObject[] hazards;
public float spawnWait =1f;
public int n = 10;
public float wait = 10f;
private int score;
private bool gameOver;
public GameObject helpText;
public GameObject overText;
void Start () {
//开启协程 用yild作为s时间间隔
StartCoroutine(SpawnWaves());
gameOver = false;
}
// Update is called once per frame
void Update () {
if(gameOver && Input.GetKeyDown(KeyCode.R))
{
UnityEngine.SceneManagement.SceneManager.LoadScene(0);
}
}
void Spawn()
{
GameObject o = hazards[Random.Range(0, hazards.Length)];
Vector3 p = new Vector3(Random.Range(-spawnValue.x, spawnValue.x), 0f, spawnValue.z);
Quaternion q = Quaternion.identity;//rotation的类型 与父物体或世界轴旋转一致
Instantiate(o, p, q);
}
IEnumerator SpawnWaves()
{
yield return new WaitForSeconds(spawnWait);
while (true)
{
int t = n;
while (t>0)
{
if (gameOver)
{
break;
}
t--;
Spawn();
yield return new WaitForSeconds(spawnWait);
}
yield return new WaitForSeconds(wait);
if (gameOver)
{
break;
}
}
}
public void AddScore(int v)
{//加分
score += v;
GameObject game = GameObject.Find("Score");
game.GetComponent<Text>().text = "Score:" + score;
}
public void GameOver()
{//游戏结束判断
gameOver = true;
helpText.GetComponent<Text>().text = "Press 'R' to restart";
overText.GetComponent<Text>().text = "Game Over";
}
}