如何快速从另一个类访问变量?

时间:2017-01-10 17:43:07

标签: c# unity3d

在我的Unity3d游戏中,我有2节课。其中一个ActsGeneral初始化变量gameManagerScript而另一个Act_0尝试访问它。

GameManager存储在object中,该对象仅存在于第一个场景中。我使用函数DontDestroyOnLoad()在其他场景中使用此类。因此,访问变量gameManagerScript的唯一方法是使用函数FindGameObjectWithTag。但是当我开始模拟时,Find没有时间找到gameManagerObject。在这里,我有错误。

Script Execution Order Settings也没有帮助。我应该检查对象是否等于null

Class ActsGeneral

void Awake()
{
    gameManagerObject = GameObject.FindGameObjectWithTag("GameManager");
    gameManagerScript = gameManagerObject.GetComponent<GameManager>();
}

班级 Act_0

void Start()
{
    // error: Object reference not set to an instance of an object
    if (actsGeneral.gameManagerScript.currentActNumber == currentLocalActNumber)
    {
    }
}

enter image description here

EDIT1

我让Find函数有更多时间来查找对象gameManagerObject,但现在我仍然有错误。所有对象和组件都已启用,我设置了脚本执行顺序设置。但它仍然无法奏效。我只是不明白其原因。

void Start()
{
    StartCoroutine("StartDelay");
}

IEnumerator StartDelay()
{
    yield return new WaitForSeconds(1.5f);
    if (actsGeneral.gameManagerScript != null)
        if (actsGeneral.gameManagerScript.currentActNumber == currentLocalActNumber)
        {
            Debug.Log("222");
        }
}

1 个答案:

答案 0 :(得分:3)

当您尝试从另一个场景中的另一个类访问数据时,最简单的方法是使用单例模式。

首先将此脚本添加到您的proyect:

using UnityEngine;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T instance;

    /**
      Returns the instance of this singleton.
   */
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                instance = (T)FindObjectOfType(typeof(T));

                if (instance == null)
                {
                    Debug.LogError("An instance of " + typeof(T) +
                                   " is needed in the scene, but there is none.");
                }
            }

            return instance;
        }
    }
}

其次将此添加到您的 ActsGeneral 类。

    using UnityEngine;

    public class ActsGeneral : Singleton<ActsGeneral> {
    ...

在您的班级 Act_0 来自其他场景

public class Act_0 : MonoBehaviour {

ActsGeneral ac;

..
void Start()
{
    ac = ActsGeneral.Instance;

    //Do something with ac ....
}

请记住,带有ActsGeneral脚本的GameObject必须在load属性上不要销毁,并且必须在第一个加载的场景中。

如果这不起作用,问题出在 ActsGeneral 脚本的Awake事件中,因此您可以为此更改它:

void Awake()
}
    gameManagerScript = GameManager.Instance;
}

并在 GameManager 脚本

using UnityEngine;

public class GameManager : Singleton<GameManager> {
...
相关问题