【问题标题】:How to access enums and variables from another C# script Unity3d如何从另一个 C# 脚本 Unity3d 访问枚举和变量
【发布时间】:2015-10-27 09:42:11
【问题描述】:

在 Unity 中,我有

public enum inven {Food,Scissors,Nothing};
public inven held;

如何从另一个脚本访问enum,更重要的是,如何访问held 变量中包含的信息。 我尝试了单例方法:

public class Singleton : MonoBehaviour {

    public static Singleton access;
    public enum inven {Nothing, Scissors, Food};
    public inven held;

    void Awake () {
    access = (access==null) ? this : access;
    }
}

创建全局变量,访问者

Singleton.inven.food //or
Singleton.access.held //respectively

但是,返回“空引用异常:对象引用未设置为对象的实例”。 我也试过用这个:

public class Accessor : MonoBehaviour {
    void Start() {
        GameObject HeldItem = GameObject.Find("Story"); //where story is the Gameobject containing the script of the enum and variable
        TextController textcontroller = Story.GetComponent<Textcontroller>(); //Where TextController is the sript containing the enum and variable
    }
}

TextController.held 等访问,返回它需要一个对象引用。这样做的正确方法是什么?

【问题讨论】:

标签: c# unity3d enums


【解决方案1】:

这是我的单身人士的做法。在我的例子中,它被称为SharedData

using UnityEngine;
using System.Collections;

public class Booter : MonoBehaviour
{
    void Start ()
    {
        Application.targetFrameRate = 30;
        GameObject obj = GameObject.Find("Globals");
        if(obj == null)
        {
            obj = new GameObject("Globals");
            GameObject.DontDestroyOnLoad(obj);
            SharedData sharedData = obj.AddComponent<SharedData>();
            sharedData.Initialize();
        }
    }
}

此脚本附加到加载的第一个场景中的对象,并在脚本执行顺序中设置为先执行。它创建一个 GameObject 来附加 SharedData 组件,然后告诉引擎在加载新关卡时不要删除该 GameObject。

然后要访问它,我这样做:

public class Interface : MonoBehaviour
{
    private SharedData m_sharedData;

    public void Initialize()
    {
        GameObject globalObj = GameObject.Find("Globals");
        m_sharedData = globalObj.GetComponent<SharedData>();

        m_sharedData.LoadData(); // This is where I use something on the singleton.
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多