1 很多第三方插件里面都在Unity提供的的生命周期Awake里面完成一些初始化。
Test2
public class Test2 : MonoBehaviour {
private Text textCom;
void Awake()
{
this.textCom = this.gameObject.GetComponent<Text>();
}
public void Fun()
{
this.textCom.text = "helloWorld";
}
}
Test1
public class Test1 : MonoBehaviour {
Test2 t;
void Awake()
{
var go = Resources.Load<GameObject>("GameObject");
var t2 = go.AddComponent<Test2>();
t2.Fun();
go.SetActive(true);
}
}
如果GameObject在初始化加载的时候是隐藏的,就会出现空引用,这个Demo里面很明显,但是放到项目里面,一天都找不到是正常事。。。