unity3D
新手上路 實例化對象出現的bug
當我年輕的在unity3D
的C#
文件中使用new
來創建一個對象的時候。
public class Single : MonoBehaviour {
private Single m_single;
m_single = new Single();
}
然后它警告了我
... You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed.MonoBehaviours can only be added using AddComponent() ...
而且你會發現m_single
一直為空。它告訴我們當你繼承了MonoBehaviour
你就不能使用關鍵字new
來實例化一個對象。
具體原來我也母雞。
public class Single : MonoBehaviour {
private Single m_single;
void Awake(){
m_single = this;
}
public static Single M_single(){
return m_single;
}
}
好了現在這個m_single
就是一個Single
的實例化對象。