通过协程调用方法会产生NullReferenceException

时间:2015-08-08 17:18:33

标签: c# unity3d coroutine

我有一些简单的方法可以打开和关闭场景中的gameObjects。如果直接调用以下工作

 public void turnOn(){
   GameObject foo = GameObject.FindWithTag("foo_tag");
   Debug.Log("1 ASSERT YES foo = "+foo);
  foo.SetActive(true); 
 }

 public void turnOff(){
 GameObject foo = GameObject.FindWithTag("foo_tag");
 Debug.Log("2 ASSERT YES foo = "+foo);
 foo.SetActive(false); 
 }

出于测试目的,我想让我的gameObjects在一定间隔后再次激活,所以我创建了一个像这样的协程。但是当使用这个协程时,turnOff和turnOn中的foo引用都是Null,为什么呢?

 void Start () {

turnOff();
StartCoroutine(ExecuteAfterTime(2));
}



IEnumerator ExecuteAfterTime(float time)
 {
  yield return new WaitForSeconds(time);

  // Code to execute after the delay
 turnOn();
 }

2 个答案:

答案 0 :(得分:2)

FindWithTag仅在我检查后返回活动的GameObjects。

http://docs.unity3d.com/ScriptReference/GameObject.FindWithTag.html

答案 1 :(得分:1)

如前所述,FindWithTag仅适用于场景中活动的对象。因为您在第一次找到它后将其设置为非活动状态: poof 。如果在第一次找到对象时缓存对象的引用,则可以使用该引用随后重新启用该对象。

例如:

private GameObject foo_reference;

public void turnOff()
{
    foo_reference = GameObject.FindWithTag( "foo_tag" );
    Debug.Log( "2 ASSERT YES foo = " + foo_reference );
    foo_reference.SetActive( false );
}

public void turnOn()
{
    Debug.Log( "1 ASSERT YES foo = " + foo_reference );
    foo_reference.SetActive( true );
}