Unity3d 实例化对象

unity3D新手上路 实例化对象出现的bug

当我年轻的在unity3DC#文件中使用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的实例化对象。

猜你喜欢

转载自www.cnblogs.com/chenjy1225/p/9661310.html
今日推荐