unity学习,希望我的博客能给喜欢unity的朋友带来帮助
前几天我们讲了飞机大战,但是界面设置却不完整,缺少文字提示等内容,接下来我们就用GUI来实现文字设置。
当我方飞机被攻击销毁后,会出现游戏结束的字样,并停止游戏,会出现重新开始的按钮,点击按钮游戏会重新开始,还可以完成按下键盘esc键游戏暂停,点击鼠标左键游戏接续的功能。
游戏界面如图所示:
代码如下:
- using UnityEngine;
- using System.Collections;
- public class GUIText : MonoBehaviour {
- public int lifeTime = 0;//我方生命值
- public int score = 0;//得分
- public static GUIText instance;//管理对象初始化,自身定为静态变量
- public Player player;//获取我方飞机
- public bool flag = false;//标志位,标志游戏的开始
- void Start()
- {
- instance = this;
- player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>();
- }
- void Update()
- {
- if (flag)
- {
- Time.timeScale = 0;//游戏结束
- }
- else
- {
- //暂停游戏
- if (Input.GetKey(KeyCode.Escape))
- {
- Time.timeScale = 0;
- }
- //开始游戏
- if (Input.GetButton("Fire"))
- {
- Time.timeScale = 1;
- }
- }
- }
- void OnGUI()
- {
-
- lifeTime = player.i;
- GUI.skin.label.fontSize = 20;
- GUI.Label(new Rect(20, 30, 150, 50), "生命值为:" + lifeTime);
- GUI.Label(new Rect(20, 70, 150, 50), "分数:" + score);
- if (lifeTime == 0)
- {
- flag = true;//游戏的结束
- GUI.skin.label.fontSize = 40;//设置字体的大小
- GUI.color = Color.red;//设置字体的颜色
- GUI.Label(new Rect(350, 100, 200, 200), "游戏结束");
- GUI.skin.button.fontSize = 20;
- GUI.color = Color.white;
- if (GUI.Button(new Rect(350, 300, 100, 100), "重新开始"))
- {
- //Application.LoadLevel("GUI");
- Application.LoadLevel(Application.loadedLevelName);
- }
- }
- }
- }
更多精彩请点击 http://www.gopedu.com/article