[英]How to access enums and variables from another C# script Unity3d
In Unity, I have 在Unity中,我有
public enum inven {Food,Scissors,Nothing};
public inven held;
How can I access the enum
and, more importantly, the information contained in the held
variable, from another script. 如何从另一个脚本访问enum
,更重要的是,包含在所held
变量中的信息。 I tried the Singleton Method: 我尝试了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;
}
}
to make global variables, accessed by 制作全局变量,由
Singleton.inven.food //or
Singleton.access.held //respectively
However, that returned "Null reference exception: Object reference not set to an instance of an object." 但是,返回“空引用异常:对象引用未设置为对象的实例”。 I also tried using this: 我也尝试使用这个:
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
}
}
accessed by TextController.held
etc, returned that it needed an object reference. 由TextController.held
等访问,返回它需要一个对象引用。 What is the proper way of doing this? 正确的做法是什么?
Here's how I do my singletons. 这是我做单身人士的方式。 In my case, it's called SharedData
. 就我而言,它称为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();
}
}
}
This script is attached to an object in the first scene that loads, and it is set in the script execution order to go first. 该脚本被附加到第一个加载的场景中的对象上,并按脚本执行顺序设置为第一个。 It creates a GameObject to attach the SharedData component to, then tells the engine not to delete that GameObject when new levels are loaded. 它创建一个GameObject来附加SharedData组件,然后告诉引擎在加载新关卡时不要删除该GameObject。
Then to access it, I do this: 然后访问它,我这样做:
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.