- Home /
Alternative way of accessing other scripts?
I have a "global" script that contains all the variables and settings and such.
I have an object that is removed after X seconds. The x seconds is defined in the global script.
Right now I do it like this:
public globalscript gls;
and then
gls = gameObject.Find("GlobalHolder").GetComponent(globalscript);
Replaced sharp parenthesis because they won't show to find the script. I have a gameobject in the world with that name that has the global script attached.
(that's in c#)
What I want to know if this is the way to do it or is there another way? Because right now I need this piece of code in every single script because they all read some value from the global script.
Thanks
I'm not the best coder but your approach seems reasonable.
Answer by Uzquiano · Apr 17, 2011 at 10:43 AM
Well... yes, if you are newie with OO programing can be hard. But I will write you one example and then you can decide :)
So if you have a global variable in your 'GlobalHolder' to keep your score, you can define it like this: NOTE that I am writing JavaScript but the diferences are minimum or any.
static var score : int;
Then in whatever script you can access your 'score' like this:
GlobalHolder.score = 2; //this is an example of access
So as you can see there is no need of make an instance of GlobalHolder, which means that there is only one instance... if you are acessing very very very often to a static varible or if the functions you are accessing static variables are very very very long you might have race conditions. But simplifying, in Unity I didn't have those kind of problems... yet ;)
Hope you can solve your stuff
Answer by Uzquiano · Apr 16, 2011 at 11:20 PM
Hi Johan,
Have you considered use static variables in your global script?
I did consider that, yes. I am kinda noobish to c# and program$$anonymous$$g overall and I have no idea what static actually does. I tried reading on google, but my puny $$anonymous$$d couldn't really understand what it does. Yes I can use global.blabla but where does it pull this from? If the script is not in the scene, how can it access it? It's a very confusing beast.