Unity- 游戏结束以及重启游戏
游戏结束以及重启游戏
思路:利用Canvas创建好覆盖全屏的结束页面,默认关闭。游戏结束时,玩家控制的对象发起委托,ui管理收下委托,显示游戏结束页面,停止游戏。游戏重新开始就是点击设置好的按钮,启动ui管理里的重新开始场景
建个游戏结束页面
编写委托类 游戏主角 以及 ui管理类的脚本
-
委托类
using System.Collections; using System.Collections.Generic; using UnityEngine; using System;public class EventHander : MonoBehaviour {//通知游戏结束public static event Action GetGameOverEvent;public static void CallGetGameOverEvent () { GetGameOverEvent ? .Invoke();} }
-
游戏主角脚本
//青蛙是否死亡private bool isdead;//游戏结束if (isdead) {EventHander.CallGetGameOverEvent();}
在游戏结束的一些判断里把
isdead
改成true
即可。 -
ui管理脚本
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;public class UiManager : MonoBehaviour {//游戏结束页面的操作public GameObject gameOverPanel;//脚本刚被调用时使用private void OnEnable() {//恢复游戏速度游戏正常进行Time.timeScale = 1; //注册接收得分的委托EventHander.GetPointEvent += OnGetPointEvent;//游戏结束的通知EventHander.GetGameOverEvent += OnGetGameOvervent;}//脚本不再被使用private void OnDisable() {EventHander.GetPointEvent -= OnGetPointEvent;EventHander.GetGameOverEvent -= OnGetGameOvervent;}///<summary>///处理游戏结束的委托///</summary>private void OnGetGameOvervent(){//显示游戏结束页面gameOverPanel.SetActive(true);//如果游戏结束页面被显示if (gameOverPanel.activeInHierarchy){//游戏速度放慢为0,游戏停止Time.timeScale = 0;}}}
这样游戏结束就完成了!
开始测试之前别忘了先关闭游戏结束页面。
DLC:如何完全停止角色的操作
在角色脚本里:
//输入输出工具组件private PlayerInput playerInput;private void Awake() {//获取输入输出组件playerInput = GetComponent<PlayerInput>();} private void Update() {if (isdead){DisbleInput();return;}}/// <summary>/// 关闭输入组件/// </summary>private void DisbleInput() {// 关闭输入组件playerInput.enabled = false;}
重启游戏
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;public class UiManager : MonoBehaviour
{///<summary>///重启游戏///</summary>public void RestartGame() {//重新加载之前活跃过的场景SceneManager.LoadScene(SceneManager.GetActiveScene().name);}
}
然后把这个函数放到按钮里去。
完成!!