延迟执行某方法
void Start (){ //重复调用 InvokeRepeating("LaunchProjectile", 1,5);//1秒后调用LaunchProjectile () 函数,之后每5秒调用一次 //调用一次 Invoke("LaunchProjectile", 5);//5秒后调用LaunchProjectile () 函数 //取消调用 CancelInvoke("LaunchProjectile"); } void LaunchProjectile(){ print("hello"); }
协同程序
同步执行
//运行结果:"Starting 0.0"和"Before WaitAndPrint Finishes 0.0"两句,2秒后打印"WaitAndPrint 2.0" //WaitAndPrint在Start函数内执行,可以视同于它与Start函数同步执行. void Start() { print("Starting " + Time.time); StartCoroutine(WaitAndPrint(2.0F)); print("Before WaitAndPrint Finishes " + Time.time); } IEnumerator WaitAndPrint(float waitTime){ yield return new WaitForSeconds(waitTime); print("WaitAndPrint " + Time.time); }
执行完成后,执行下面的
//运行结果:0秒时打印"Starting 0.0",2秒后打印"WaitAndPrint 2.0"和"Done 2.0" // 运行WaitAndPrint直到完成。 IEnumerator Start(){ print("Starting " + Time.time); yield return StartCoroutine(WaitAndPrint(2.0F)); print("Done " + ime.time); } IEnumerator WaitAndPrint(float waitTime) { yield return new WaitForSeconds(waitTime); print("WaitAndPrint " + Time.time); }
同步执行
//StopCoroutine停止协同程序 IEnumerator Start() { StartCoroutine("DoSomething", 2.0F); yield return new WaitForSeconds(1); StopCoroutine("DoSomething"); }
IEnumerator DoSomething(float someParameter) { while (true) { print("DoSomething Loop"); yield return null; } }
子/父级关系
设置子/父级关系
//B为A的父级 A.transform.parent = B.transform;
获取所有子物体
foreach (Transform item in this.transform) { print(item.name); }
旋转/角度
限制旋转角度
/// <summary> /// 限制旋转角度 /// </summary> /// <param name="angle" />要旋转的Deg /// <param name="min" />最小角度 /// <param name="max" />最大角度 /// <returns>符合标准的deg</returns> public static float ClampAngle(float angle, float min, float max) { if (angle < -360) angle += 360; if (angle > 360) angle -= 360; return Mathf.Clamp(angle, min, max); }
限制旋转最大扭距
/// <summary> /// 限制旋转最大扭距 /// </summary> /// <param name="angleTarget">要达到的deg /// <param name="angleNow">当前角度 /// <returns>符合标准的deg</returns> public static float reviseMaxAngle(float angleTarget, float angleNow) { float max = 160; float DValue = angleTarget - angleNow; if (DValue < -360) DValue += 360; if (DValue > 360) DValue -= 360; if (DValue > max) { DValue = max; } else if (DValue < -max) { DValue = -max; } angleTarget = angleNow + DValue; return angleTarget; }
Other
确定目标可见性(α透明)