繁体   English   中英

如何从另一个C#脚本Unity3d访问枚举和变量

[英]How to access enums and variables from another C# script Unity3d

在Unity中,我有

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

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

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等访问,返回它需要一个对象引用。 正确的做法是什么?

这是我做单身人士的方式。 就我而言,它称为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.
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM