C# 通过协同路由调用方法会产生NullReferenceException
我有一些简单的方法来打开和关闭场景中的游戏对象。如果直接调用,则执行以下工作C# 通过协同路由调用方法会产生NullReferenceException,c#,unity3d,coroutine,C#,Unity3d,Coroutine,我有一些简单的方法来打开和关闭场景中的游戏对象。如果直接调用,则执行以下工作 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
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);
}
出于测试的目的,我想让我的游戏对象在一段时间后再次激活,所以我创建了一个类似这样的协同程序。但是当使用这个协程时,关闭和打开中的foo引用都是空的,为什么
void Start () {
turnOff();
StartCoroutine(ExecuteAfterTime(2));
}
IEnumerator ExecuteAfterTime(float time)
{
yield return new WaitForSeconds(time);
// Code to execute after the delay
turnOn();
}
FindWithTag只返回我上次检查的活动游戏对象
如前所述,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 );
}
您应该传递要打开或关闭的游戏对象的引用。一旦游戏对象不处于活动状态,带有标记的find将返回null。