zoukankan      html  css  js  c++  java
  • MonoBehaviour的单例模式

            我们有一个继承自MonoBehaviour的类是用来做对象交互动作的,想做成单例的,写成通用的方法报错。

    private static Communication instance;
        public static Communication GetInstance()
        {
          if(instance==null){
            instance=new Communication();
            }
            return instance;
        }


    提示:You are trying to create a MonoBehaviour using the 'new' keyword.  This is not allowed.  MonoBehaviours can only be added using AddComponent().  Alternatively, your script can inherit from ScriptableObject or no base class at all


    网上找到了解决方案,系统会自动创建MonoBehaviour 对象,在其awake时候设置其instane即可。

    正确代码如下:

    private static Communication instance;
        public static Communication GetInstance()
        {
            return instance;
        }


    void Awake() {
    instance = this;
    }

  • 相关阅读:
    GC(垃圾分代收集)
    排序算法总结
    Redis中的数据结构
    事务的隔离性(续篇)
    手写Spring mvc框架 (二)
    MySql日志与事务的隔离级别
    手写Spring mvc框架 (一)
    IO流
    随笔三(Ajax)
    关于博主noble_
  • 原文地址:https://www.cnblogs.com/secbook/p/2655374.html
Copyright © 2011-2022 走看看