I want to create a set of global variables in such a way that every script in my application can read and modify those variables.
Here is a C# script for my global variables;
using UnityEngine;
using System.Collections;
public class [B]GlobalVars[/B] : MonoBehaviour {
public static bool myGlobalBoolVar = false;
public static int myGlobalIntVar = 0;
public static float myGlobalFloatVar = 1.2f;
public static Color myGlobalColorVar = Color.black;
public static Transform myGlobalTransformVar; // [COLOR="#8b0000"][I]How to initialize this variable?[/I][/COLOR]
public static Vector3 myGlobalVector3Var = new Vector3(1.11f,2.22f,3.33f);
}
- Is this right way defining and initializing global variables?
Here is a C# script to updating the global variables via Inspector;
using UnityEngine;
using System.Collections;
public class [B]GlobalVarTester[/B] : MonoBehaviour {
[COLOR="#8b0000"][B]// If I use "get" and "set" for a variable, then that variable does not appear in Inspecto[/B]r
[B]// If I do not use "get" and "set", how can update the global variable in __computationally efficient manner__?[/B][/COLOR]
public bool myBoolVar;[I]// { get {return GlobalVars.myGlobalBoolVar;} set {GlobalVars.myGlobalBoolVar = value;}} [/I]
public int myIntVar { get {return GlobalVars.myGlobalIntVar;} set {GlobalVars.myGlobalIntVar = value;}}
public float myFloatVar { get {return GlobalVars.myGlobalFloatVar;} set {GlobalVars.myGlobalFloatVar = value;}}
public Color myColorVar { get {return GlobalVars.myGlobalColorVar;} set {GlobalVars.myGlobalColorVar = value;}}
public Transform myTransformVar { get {return GlobalVars.myGlobalTransformVar;} set {GlobalVars.myGlobalTransformVar = value;}}
public Vector3 myVector3Var { get {return GlobalVars.myGlobalVector3Var;} set {GlobalVars.myGlobalVector3Var = value;}}
public double myOtherVar =1234.567;
// Update is called once per frame
void Update () {
[B][COLOR="#8b0000"] // Isn't it inefficient if I do the following assignments repeatedly here in Update function?[/COLOR][/B]
GlobalVars.myGlobalBoolVar = myBoolVar;
/*
GlobalVars.myGlobalIntVar = myIntVar;
GlobalVars.myGlobalFloatVar = myFloatVar;
GlobalVars.myGlobalColorVar = myColorVar;
GlobalVars.myGlobalTransformVar = myTransformVar;
GlobalVars. myGlobalVector3Var = myVector3Var;
*/
if (GlobalVars.myGlobalBoolVar) {
Debug.Log("myGlobalBoolVar is TRUE");
} else {
Debug.Log("myGlobalBoolVar is FALSE");
}
}
}
- What is the computationally efficient way to update global variables using Inspector?
- Is there a way implementing “OnValueChanged” kind of behavior/mechanism in C#/Unity?
-Adamo