在Unity中,你可以通过以下几种方式来定义全局变量:
-
静态类变量:你可以创建一个静态类,并在其中定义静态变量,这样就可以在整个项目中访问这些变量。
public static class GlobalVariables { public static int globalInt = 10; public static string globalString = "Hello"; }
在其他脚本中,你可以直接通过
GlobalVariables.globalInt
或GlobalVariables.globalString
来访问这些全局变量。 -
单例模式:你可以创建一个单例类,在其中定义全局变量,并通过实例化这个单例类来访问全局变量。
public class GlobalVariables : MonoBehaviour { public static GlobalVariables instance; public int globalInt = 10; public string globalString = "Hello"; void Awake() { if (instance == null) { instance = this; DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); } } }
通过
GlobalVariables.instance.globalInt
或GlobalVariables.instance.globalString
来访问这些全局变量。 -
PlayerPrefs:你也可以使用PlayerPrefs来存储全局变量的值,这样可以在应用程序的不同场景和会话之间进行持久化存储。
// 存储全局变量的值 PlayerPrefs.SetInt("globalInt", 10); PlayerPrefs.SetString("globalString", "Hello"); // 读取全局变量的值 int myInt = PlayerPrefs.GetInt("globalInt"); string myString = PlayerPrefs.GetString("globalString");