五。设计计算分数和重新开始
1.首先,新建一个UGUI的Text,移到合适位置,设置锚点,固定在一个地方,然后在游戏管理器里面加上以下参数和方法
进行赋值
然后打开Enemy脚本,加入一行代码
运行,射中陨石便可以看到积分更新。
2.重新开始的话,我的思路是重新加载这个场景,这也是比较简单的实现方式,在设置之前,先对场景的灯光信息进行保存,如下进行烘焙
在菜单栏的Window下,找到Lighting里面的Setting,打开如下
3.回到M_GameManager脚本里面,添加如下参数和方法,注意要添加Using UnityEngine.UI和Using UnityEngine.SceneManager两个命名空间,一个是ui的,一个是场景转换的
4.然后打开Player脚本,添加下面两行代码
5.回到Unity,在新建一个Text,添加如下文字
6.再把Text赋值给游戏管理器的值上
7.打开File-BuildSetting 把自己的MainScene场景拖进去,
然后运行,玩家销毁后,按R键重新开始
8.完整脚本
***************************M_GameManager*************
***********************************************Player******************************
using System.Collections;using System.Collections.Generic;using UnityEngine;[System.Serializable]//可显示public class PlayerClampBounder//移动的X,Z最大范围或者最小范围类{ public float MaxX; public float MaxZ; public float MinX; public float MinZ;}public class Player : MonoBehaviour { public PlayerClampBounder Bounder;//边界范围 public float MoveSpeed;//移动速度 public float ShotDuratime = 0.3f;//发射的间隔时间 public GameObject BulletPrefab;//子弹的预制体,在unity进行赋值 private Transform BulletPoint;//子弹生成的位置 public GameObject PlayerExplosion;//玩家爆炸 private AudioSource PlayerAS;//玩家的声音组件 public AudioClip PlayerExplosionClip;//玩家爆炸的音频 public AudioClip PlayerShootClip;//玩家发射子弹的音频 void Start () { BulletPoint = transform.Find("BulletPoint");//获取子物体BulletPoint PlayerAS = GetComponent<AudioSource>();//获取音频组件 } // Update is called once per frame void Update () { MoveMent(); ShotBullet(); } public void MoveMent()//控制移动的方法 { float Horizontal = Input.GetAxis("Horizontal");//获取水平输入轴 float Vertical = Input.GetAxis("Vertical");//获取垂直输入轴 if (transform.position.x >= Bounder.MaxX && Horizontal > 0)//如果当前x位置大于等于边界范围,且还在向这个方向运动,也就是说还按下了向右,就让水平输入值为0,也就不会再继续向右 { Horizontal = 0; } else if (transform.position.x <= Bounder.MinX && Horizontal < 0)//同理 { Horizontal = 0; } else if (transform.position.z >= Bounder.MaxZ && Vertical > 0) { Vertical = 0; } else if (transform.position.z <= Bounder.MinZ && Vertical < 0) { Vertical = 0; } transform.Translate(Horizontal*MoveSpeed*Time.deltaTime, 0, Vertical*Time.deltaTime*MoveSpeed);//移动 } private void ShotBullet() { ShotDuratime -= Time.deltaTime; if (ShotDuratime <= 0&&Input.GetMouseButton(0))//当时间到了且按下了鼠标左键 { if (!PlayerAS.isPlaying) { PlayerAS.clip = PlayerShootClip; PlayerAS.Play(); } Instantiate(BulletPrefab, BulletPoint.position, Quaternion.identity);//生成子弹 ShotDuratime = 0.3f;//重新设置间隔时间 } } private void OnTriggerEnter(Collider other) { if (other.tag == "Enemy")//碰到敌人 { if (!PlayerAS.isPlaying) { PlayerAS.clip = PlayerExplosionClip; ; PlayerAS.Play(); } Destroy(other.gameObject);//销毁敌人 GameObject obj = Instantiate(PlayerExplosion, transform.position, Quaternion.identity);//生成爆炸物 Destroy(obj, 0.3f);//销毁爆炸物 M_GameManager._instance.ShowRestartText(); M_GameManager._instance.CanRestart = true; Destroy(gameObject,0.2f);//销毁自己 } }}