unity3D制作新游戏和退出游戏13
点击新游戏按钮 所有数据刷新
创建一个空物体存放所有的Target怪
数据归零

将Target放入
ctrl+d复制一份
显示一个怪物并赋值一份target

让每个格子中存在一个怪
双击居中画面


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TargetManager : MonoBehaviour
{
//16.方便其他文件调用
public static TargetManager _instance;
//1.获取我们设置的四种怪物:控制怪物的生成或销毁(显示或隐藏) 最开始是都不显示
//2.建立数组
public GameObject[] monsters;
//6.获得激活状态的怪物
public GameObject activeMonster = null;
//17.赋值
private void Awake()
{
_instance = this;
}
//9.调用测试
private void Start()
{
//10.遍历初始化目标怪的状态以及boxcollider状态
foreach (GameObject monster in monsters)
{
monster.GetComponent<BoxCollider>().enabled = false;
monster.SetActive(false);
}
//ActiveMonster();
//12.调用迭代器方法:先注释上一句的直接调用
StartCoroutine("AliveTimer");
}
//3.是否激活各种状态函数
private void ActiveMonster()
{
//4.随机激活:得到index
int index = Random.Range(0, monsters.Length);
//5.激活怪物:需要先获得激活状态的怪物
//赋值
activeMonster = monsters[index];
//7.激活
activeMonster.SetActive(true);
//8.激活box collider
activeMonster.GetComponent<BoxCollider>().enabled = true;
//14.调用
StartCoroutine("DeathTimer");
}
//11.协程控制迭代器 设置怪物生成的等待时间
IEnumerator AliveTimer()
{
yield return new WaitForSeconds(Random.Range(1, 5));
ActiveMonster();
}
//14.控制死亡迭代器 使激活状态的怪变为未激活状态
private void DeActiveMonster()
{
if (activeMonster != null)
{
activeMonster.GetComponent<BoxCollider>().enabled = false;
activeMonster.SetActive(false);
activeMonster = null;
}
//14.再次激活
StartCoroutine("AliveTimer");
}
//设置死亡时间
IEnumerator DeathTimer()
{
yield return new WaitForSeconds(Random.Range(3, 8));
DeActiveMonster();
}
//15.更新怪物 在其他脚本中调用此方法
public void UpdateMonsters()
{
//关闭所有协程
StopAllCoroutines();
if (activeMonster != null)
{
activeMonster.SetActive(false);
activeMonster = null;
}
StartCoroutine("AliveTimer");
}
}
更新
赋值targetGO

注册newgame按钮

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public static GameManager _instance;
//1.设置暂停
public bool isPaused = true;
//2.获得组件
public GameObject menuGo;
//3.设置数组
public GameObject[] targetGOs;
private void Awake()
{
_instance = this;
Pause();
}
private void Update()
{
//判断是否按下esc键 是并暂停游戏
if (Input.GetKeyDown(KeyCode.Escape))
{
Pause();
}
}
private void Pause()
{
isPaused = true;
menuGo.SetActive(true);
Time.timeScale = 0;
//隐藏鼠标图标
Cursor.visible = true;
}
private void UnPause()
{
isPaused = false;
menuGo.SetActive(false);
Time.timeScale = 1;
Cursor.visible=false;
}
public void ContinueGame()
{
UnPause();
}
public void NewGame()
{
//3. 要更新9个位置的怪物 先设置数组
foreach(GameObject targetGO in targetGOs)
{
targetGO.GetComponent<TargetManager>().UpdateMonsters();
}
UIManager._instance.shootNum = 0;
UIManager._instance.score = 0;
UnPause();
}
}
退出游戏
build之后生效
public void QuitGame()
{
Application.Quit();
}
注册按钮

设置UI锚点




浙公网安备 33010602011771号