AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > Unity3D

Unity 2D 坦克游戏教程(8):GUIText 基本UI

51自学网 2014-05-24 http://www.51zixue.net

下载本项目的文件包请点击:第八部分:计分板.
本指导涵盖了一些基本的UI文本,任何外星人发生死亡时,都能够记录分数。

本教程将涉及

  • 更新 GUIText 分数信息

基本的记分牌

点击GameObject -> Create Other -> GUIText


 

GUI Text

把这个对象命名为“Score”。创建如下的脚本,命名为“ScoreController”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using UnityEngine;
using System.Collections;
 
public class ScoreController : MonoBehaviour {
 
public int score = 0; // The player's score.
private int previousScore = 0; // The score in the previous frame.
 
void Awake ()
{
}
 
void Update ()
{
// Set the score text.
guiText.text = "Score: " + score;
 
// Set the previous score to this frame's score.
previousScore = score;
}
}

现在分数的游戏对象看起来应该是这个样子:

Score game object

注意:GUI元素与其他游戏对象的行为方式不同,“transform”的坐标不在世界坐标,而是屏幕坐标。因此,如果想要GUI元素出现在屏幕上,必须限制其在0到1之间。否则,你将看不见文本。请确认X和Y轴的坐标都是在0到1之间。

现在,打开AlienController 脚本,并添加如下脚本更新:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using UnityEngine;
using System.Collections;
 
public class AlienController : MonoBehaviour {
 
public float alienSpeed = .02f;
private ScoreController score;
 
// Use this for initialization
void Start () {
score = GameObject.Find("Score").GetComponent();
}
 
// Update is called once per frame
void Update () {
transform.position += new Vector3(0, -alienSpeed, 0);
}
 
void OnTriggerEnter2D(Collider2D col)
{
// If the alien hits the trigger...
if (col.gameObject.tag == "Player") {
Destroy (gameObject);
 
if(score.score >= 100)
score.score -= 100;
else if(score.score > 0)
score.score = 0;
 
} else if (col.gameObject.tag == "Terrain") {
score.score += 100;
Destroy (gameObject);
}
}
 
}

现在,如果外星人撞到地面死亡的话,分数就会更新。结果如下图:

score


 

接下来:

在下一篇文章中,将介绍游戏中动态生成敌人。

原文链接:Unity 2D Tank Game: Part VIII -Basic UI With GUIText


建议使用电驴(eMule)下载分享的资源。

说明
:本教程来源互联网或网友分享或出版商宣传分享,仅为学习研究或媒体推广,51zixue.net不保证资料的完整性。
 
上一篇:Unity 2D 坦克游戏教程(7):碰撞处理  下一篇:Unity 2D 坦克游戏教程(9):创建敌人