Unity 之 AfterFixedUpdate,在所有 GameObject FixedUpdate 后执行
2016-12-07 13:44
429 查看
目的
FixedUpdate 在不同的 GameObject 互相之间是没有执行顺序的,我们并不能知道哪个 GameObject 先执行 FixedUpdate。但是,有的时候我们仍然希望某个 GameObject 在其他所有 GameObject 执行 FixedUpdate 之后能执行一个指定的函数。
思路
(图1)
观察上图 Unity 生命周期(片段)中 Physics 部分。FixedUpdate 后,执行了 yield WaitForFixedUpdate,然后进行物理更新。
我们发现,可以尝试用协程实现。
实现 AfterFixedUpdate
1、创建一个 C# 脚本,命名为 TryAfterFixedUpdate,代码如下using UnityEngine; using System.Collections; public class TryAfterFixedUpdate : MonoBehaviour { [SerializeField] string text; int a = 0; void FixedUpdate () { a++; Debug.Log (string.Format ("FixedUpdate {0} {1}", a, text)); StartCoroutine (AfterFixedUpdate ()); } IEnumerator AfterFixedUpdate () { Debug.Log (string.Format ("AfterFixedUpdate {0} {1}", a, text)); yield return new WaitForFixedUpdate (); Debug.Log (string.Format ("AfterYield {0} {1}", a, text)); } }
2、创建两个空的 GameObject,分别命名为 A B
3、将 TryAfterFixedUpdate 脚本分别拖放到 A 和 B 上,并设置 text 分别为 "a" 和 "b"
(图2)
4、执行脚本,我们得到了如下结果。可见,成功实现了我们的目的
(图3)
相关文章推荐
- unity中gameobject设为true后其身上脚本不会立即执行!!
- Unity删除一个GameObject下的所有子项
- unity gameObject之间的调用函数的方法
- [Unity 笔记] 代码中获取和修改GameObject的shader属性
- unity GameObject.SendMessage调用的方法有多个参数的调用方法
- 关于unity中的gameobject.active的问题。
- Unity GameObject.activeSelf, GameObject.activeInHierarchy,GameObject.SetActive和SetActiveRecursively
- [self performselector: withObject: afterDelay:];一定时间后执行某个方法
- Unity ----- 对象池GameObjectPool
- Unity GameObject.activeSelf, GameObject.activeInHierarchy,GameObject.SetActive和SetActiveRecursively
- childObject.transform.parent.gameObject Unity得到gameObject后,取GameObject的父
- 【Unity游戏开发之四】GameObject.Find()、Transform.Find查找隐藏对象
- 查找所有GameObject的方法
- UNITY gameobject代码中setacvtive(false)与面板中直接去掉勾 效果不一样
- Unity GameObject.activeSelf, GameObject.activeInHierarchy,GameObject.SetActive和SetActiveRecursively
- [Unity 笔记] 在Object上挂在两个script, 其中一个的初始化代码先于另一个执行
- Unity3D控制gameobject脚本执行的顺序
- Unity游戏暂停(Update与FixedUpdate区别)
- 【Unity3D基础概念】给初学者看的Unity概览(一):GameObject,Compoent,Time,Input,Physics
- Unity GameObject.activeSelf, activeInHierarchy, SetActive和SetActiveRecursively区别