延迟执行某方法
void Start () {
//重复调用
InvokeRepeating("LaunchProjectile", 1,5);//1秒后调用LaunchProjectile () 函数,之后每5秒调用一次
//调用一次
Invoke("LaunchProjectile", 5);//5秒后调用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;
//B为A的父级
A.transform.parent = B.transform;
获取所有子物体
- foreach (Transform item in this.transform)
- {
- print(item.name);
- }