是否可以在Unity中创建“全局”类实例?

时间:2016-02-02 18:10:05

标签: c# unity3d

抱歉这个愚蠢的问题,我是Unity脚本的新手。

我需要创建一个类实例,它需要由任何场景中的组件共享和访问。

我可以轻松地创建一个静态类并在组件脚本中使用它,但是我的类有大量的网络和处理,因为我只需要处理一次,所以只创建一个实例会很好。

是否可以做类似的事情? 例如:

// The class which I need to create and share
public class DemoClass {
     MyExampleClass example;
     public DemoClass (){
            example = new MyExampleClass ();
      }
     public MyExampleClass GetClassInstance(){
            return example;
      }
 }

// The "Global Script" which I'll instantiate the class above
public class GlobalScript{
    MyExampleClass example;
    public void Start(){
         DemoClass demoClass = new DemoClass();
         example = demoClass.GetClassInstance();
     }

     public MyExampleClass getExample(){
         return example;
      }
  }

  // Script to insert in any component
  public class LoadMyClass : MonoBehaviour {
      public void Start(){
          // this is my main issue. How can I get the class Instance in the GlobalScript?
          // the command below works for Static classes.
          var a = transform.GetComponent<GlobalScript>().getExample(); 
       }
    }

对此的任何暗示都将非常感激。

感谢。

2 个答案:

答案 0 :(得分:3)

在一个简单的层面上,似乎单步模式将成为可行的方法(如上所述)。虽然不是来自官方的Unity资源,但这里有一个指向教程的链接,还有一个相当好的文档代码示例。

http://clearcutgames.net/home/?p=437

Singleton示例:

using UnityEngine;

public class Singleton : MonoBehaviour
{
    // This field can be accesed through our singleton instance,
    // but it can't be set in the inspector, because we use lazy instantiation
    public int number;

    // Static singleton instance
    private static Singleton instance;

    // Static singleton property
    public static Singleton Instance
    {
        // Here we use the ?? operator, to return 'instance' if 'instance' does not equal null
        // otherwise we assign instance to a new component and return that
        get { return instance ?? (instance = new GameObject("Singleton").AddComponent<Singleton>()); }
    }

    // Instance method, this method can be accesed through the singleton instance
    public void DoSomeAwesomeStuff()
    {
        Debug.Log("I'm doing awesome stuff");
    }
}

如何使用单身人士:

// Do awesome stuff through our singleton instance
Singleton.Instance.DoSomeAwesomeStuff();

答案 1 :(得分:2)

阅读方便命名的Singleton。它们是一种Unity之前的软件设计模式,可以满足只有一个这样的实例的需求。在线有许多Unity特定的通用示例。

从附带的链接中, &#34;&#34;为什么选择Singleton?&#34;,你可能会问。首先,那么,单身人士是什么?它是一种设计模式,它将类的实例化限制为一个对象。而且,如果您在这里,您可能希望基本上使用它来实现全局变量。对于任何其他用途,只需将其作为起点。 在Unity中使用单例而不是静态参数和方法的优点基本上是:

  1. 静态类在首次引用时是延迟加载的,但必须有一个空的静态构造函数(或者为您生成一个)。这意味着如果您不小心并且知道自己在做什么,这会更容易搞乱和破坏代码。至于使用Singleton模式,你自动已经做了很多简洁的事情,比如使用静态初始化方法创建它们并使它们不可变。
  2. Singleton可以实现一个接口(Static不能)。这允许您构建可用于其他Singleton对象的合约,或者您可以使用的任何其他类。换句话说,你可以拥有一个包含其他组件的游戏对象,以便更好地组织!
  3. 您也可以从基类继承,您可以使用静态类继承。
  4. 对于Unity而言,还有一个额外的概念,即所述脚本将被分配给通常在新的级别加载时将被销毁的游戏对象。这就是为什么通常采用以Unity为中心的方法来防止在加载新关卡时破坏游戏对象。

    DontDestroyOnLoad(singleton);
    

    我强烈建议您熟悉一般与游戏开发有关的设计模式。在适当的地方使用时,它们很有趣且非常强大。

相关问题