demo优化及协同程序简单介绍
显示分数
- 创建一个空物体添加GuiText组件并绑定脚本score
- 在score中实现一个增加分数的方法
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
| using System.Collections; using System.Collections.Generic; using UnityEngine; public class score : MonoBehaviour { private GUIText m_guitext; private int Score; void Start () { //获取到GUITEXT组件 m_guitext = gameObject.GetComponent<GUIText>(); //分数初始化 Score = 0; } void Update () { } void AddScore() { //增加分数 Score += 10; m_guitext.text = "分数:" + Score; } }
|
盒子销毁后随机出现金币
- 创建一个金币模型,并绑定脚本gold
- 在脚本中实现金币的自动旋转以及碰撞后销毁并增加得分
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
| using System.Collections; using System.Collections.Generic; using UnityEngine; public class gold : MonoBehaviour { //获取金币transform组件 private Transform m_t; //获取分数 private GameObject score; void Start () { m_t = gameObject.GetComponent<Transform>(); score = GameObject.Find("score"); } void Update () { //每一帧物体环绕世界的y轴旋转10度 m_t.Rotate(Vector3.forward,10f); } private void OnTriggerEnter(Collider other) { if (other.gameObject.name == "main") { //销毁自身 Destroy(gameObject); score.SendMessage("AddScore"); } } }
|
这里出现了一个新的函数 “SendMessage(String)”,可以用来调用指定对象脚本中的方法
协同程序
概念简介
- 在U3D游戏只有一个主线程,但是一个线程可以存在多个协同程序
- 协同程序不是线程但是类似于线程,主要区别在于线程是由系统控制的,而协程是由程序控制的
- 开启一个线程需要很大的性能开销而且需要考虑多个线程中资源的互斥访问问题
- 协程由程序控制,优点是性能开销小,但是在一个主线程内同时只能有一个协程在运行,其他协程必须暂停
- 协程只能在继承了MonoBehaviour的子类中使用
协程语法
代码书写
1 2 3 4 5 6 7
| IEnumerator methodName(Object parameter1,Object parameter2,...){ // to do something yield return YieldInstruction/other/null; // to do something else } //协程必须返回一个 IEnumerator类型 //yield return xxx 语句表示 等待 xxx完成后执行之后的语句
|
开启与关闭协程
- StartCoroutine(IEnumerator routine);
优点:灵活,性能开销小。
缺点:无法单独的停止这个协程,如果需要停止这个协程只能等待协同程序运行完毕或则使用StopAllCoroutine();方法。
- StartCoroutine (methodName:string, value : object = null);
优点:可以直接通过传入协同程序的方法名来停止这个协程:StopCoroutine(string methodName);
缺点:性能的开销较大,只能传递一个参数。
使用案例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| using System.Collections; using System.Collections.Generic; using UnityEngine; public class test : MonoBehaviour { void Start () { Debug.Log(1); Debug.Log(2); //启动协程 StartCoroutine("task"); Debug.Log(4); } IEnumerator task() { //等待两秒钟 yield return new WaitForSeconds (2); Debug.Log(3); } }
|