How to make a global variable in Unity?
im trying to make a global variable so other scripts can do stuff with it. How do i make a variable global?
edit using java
Answer by AngryOldMan · Mar 05, 2011 at 05:20 PM
I'm pretty sure this has already been answered but you can always put
static var
infront of something and that makes it accesible from other scripts.
does this still work it doesn't seem to do you have to put it in both scripts i tried that too and it didnt work
you don't need to put the definition both places. in c#, you would write static in front of the variable, then in the other script you can access by typing
origscriptname.variablename
Answer by cregox · Sep 04, 2013 at 12:15 AM
Use `Singleton`s!
They're **much** better than using static.
Grab the singleton script above and simply use it as such:
public class MyClass : MonoBehaviour {
void Awake () {
Debug.Log(Manager.Instance.myGlobalVar);
}
}
Manager.cs
public class Manager : Singleton<Manager> {
public string myGlobalVar = "whatever";
}
Hi Cawas, How do I do this in some if
statement in the Update
method? I have the following Update
and LateUpdate
, and I would like to use the latest results of Update
in LateUpdate
; i.e. be able to use currentPose
and target$$anonymous$$odel
in the updateAgainLater
method. How do I store the currentPose
and target$$anonymous$$odel
contents immediately, so I can use them in LateUpdate
?
void Update()
{
Vector3[] latestPositions;
Quaternion[] latestOrientations;
// Get the pose data in one call.
if (Actors.getLatestPose(actorID, out latestPositions, out latestOrientations))
{
// Update both the pose and the model.
updateActor(currentPose, latestPositions, latestOrientations);
update$$anonymous$$odel(currentPose, target$$anonymous$$odel);
}
}
void LateUpdate()
{
updateAgainLater();
}
Thanks
Answer by jashan · Mar 05, 2011 at 05:20 PM
You can use the "static" modifier. In C#, that would be
public static int myInt = 0;
It took me forever to find this out, so I thought I would mention it here.
If you create a global variable called myGlobal inside a class called GlobalVars, you access that global variable with GlobalVars.myGlobal
.
Answer by stpharis · Jul 26, 2017 at 04:19 PM
Hi,
This tutorial explains very clearly and simply how to create global variables using Singletons!
https://www.youtube.com/watch?v=CPKAgyp8cno
Hope it helps!
Answer by himanshugupta159 · Jan 25, 2019 at 07:38 AM
Written a blog related to the question which gives the indepth information related to varible scope. link:https://unfragilecoding.blogspot.com/2019/01/variable-scope.html