- Home /
How do you return variables from other scripts?
Ok, I know the first admin to see this will think "This has been asked before! ~delete~" but I just don't understand! The other instances where this has been asked seems to be quite specific to their needs. Rather than saying "This is my code, make it do this" can someone please explain to me, using a random piece of code, how to call a variable from another script? If you do need to see my script I'll put it on but I'd prefer to learn this rather than copy it :) Thanks.
Answer by whydoidoit · Jul 15, 2012 at 02:25 PM
JS:
anotherGameObject.GetComponent(ScriptName).myVariable = 1;
GameObject.Find("someName").GetComponent(ScriptName).DoSomething();
C#:
anotherGameObject.GetComponent<ScriptName>().myVariable = 1;
//Find the first instance of the script on the object or any children
GameObject.Find("someName").GetComponentInChildren<ScriptName>().DoSomething();
...and look at the Unity manual from http://docs.unity3d.com/Documentation/ScriptReference/index.html
. The part above is under "Accessing Other Components."
There are a lot of other good sections that are buried 6 links down from somewhere -- you just have to use a combination of the links in Unity combined with Google and be prepared to bookmark.
Ok, I think I get it but I'm returning an error on this:
if(gameObject.GetComponent<HealthBar>().sta$$anonymous$$a >= 0.0)
Any ideas (i have a script named "HealthBar" with a variable "sta$$anonymous$$a" in it and its attached to the same object as this script) - Thanks for your answers as well!
Edit: error says: "The type or namespace name `HealthBar' could not be found. Are you missing a using directive or an assembly reference?"
No, its C#, and I'm sure it is. The variable in the other script is java but ^ this one is in C# because its a modified script from somewhere else. Thanks.
well if that's in JS it should be
gameObject.GetComponent(HealthBar).sta$$anonymous$$a
Just make sure you sta$$anonymous$$a variable is accessible.
In C#:
gameObject.GetComponent<HealthBar>().sta$$anonymous$$a
Just make sure that the healthbar is attached with the current gameObject that your workin on.
Sorry to be the bearer of bad news. It's a total killer - you really should stick with one language - makes life a lot easier.
Answer by NothAU · Jul 15, 2012 at 02:23 PM
I'm fairly certain if you declare the variable as "Public Static (Type) (VariableName)", it should be accessible outside of the script by using "ScriptName.VariableName".
But note that declaring it as static means there will only be 1 of that variable, so you don't want to use it for something that multiple objects have, like an enemy's health.