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

cat*_*ror 4 c# unity-game-engine

抱歉问了这个愚蠢的问题,我是 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(); 
       }
    }
Run Code Online (Sandbox Code Playgroud)

对此的任何提示将不胜感激。

谢谢。

ket*_*red 7

从简单的角度来看,单例模式似乎是正确的选择(如上所述)。虽然不是来自官方 Unity 资源,但这里有一个教程的链接以及一个记录得相当好的代码示例。

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

单例示例:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

如何使用单例:

// Do awesome stuff through our singleton instance
Singleton.Instance.DoSomeAwesomeStuff();
Run Code Online (Sandbox Code Playgroud)