2013-05-26 84 views
0

我试图使用帮助函数为了使函数暂停几秒钟,但它不执行等待函数。在触发函数内部使用帮助函数

这就是我一直在使用的代码:

代码:

public class Triggers : MonoBehaviour { 
    IEnumerator wait(float seconds) { 
     Debug.Log("In wait"); 
     yield return new WaitForSeconds(seconds); 
     Debug.Log("after wait"); 
    } 

    void OnTriggerEnter(Collider _collider) 
    { 
     Debug.Log("Destroy"); 
     gameObject.SetActive(false); 
     Debug.Log("Before wait"); 
     wait(5); 
     Debug.Log("activate"); 
     gameObject.SetActive(true); 
    } 
} 

我会很感激一些帮助。

回答

2

我解决它通过只停用子对象,它是实际的“物理”的对象,我想隐藏的是无形的碰撞父对象。因此,现在父对象保持活动状态,计算时间并且物理对象“立方体”显示并在n秒后重新出现。

public class Triggers : MonoBehaviour 
{ 
    IEnumerator wait (float seconds) 
    { 
     Debug.Log ("In wait"); 
     GameObject go = GameObject.Find ("Cube"); 
     go.SetActive(false); 
     yield return new WaitForSeconds(seconds); 
     Debug.Log ("after wait"); 
     go.SetActive (true); 
    } 

    void OnTriggerEnter (Collider _collider) 
    { 
     Debug.Log ("Destroy"); 
     Debug.Log ("Before wait"); 
     StartCoroutine (wait (5)); 
     Debug.Log ("activate"); 

    } 
+0

干得好。感谢您发布最终结果。 ;-) –

0

试试这个:

StartCoroutine(wait(5)); 

而不是简单地 “等待(5)”。

这是协程在C#中的工作方式,如果我记得很清楚......

+0

它给我错误,因为游戏对象是不活动的,Coroutine无法启动。其他解决方案? – Red

+0

如果这不符合您的预期,可以尝试将脚本附加到对象层次结构中的另一个“Monobehaviour”。 –

+0

如果您将脚本附加到空的父'GameObject',并激活/停用您的'gameObject'会发生什么情况,该对象将作为此空对象的子对象移动? –