- Home /
accessing and changing a float variable in another script
HI I need to get a float variable that is stored in one script and change the value of that float using another script could you please tell me how to get that value and change it in JavaScript. thank you in advance:) this is the code I need to access:`public var Iron = 500f;` the value Iron will be changing over time.
Did you google this or notice the other 5000 questions/answers that are the same, or the page in the Scripting Reference all about this?
yes I have googled it but none of the answers work how I need them to or they are for c#, as for the scripting reference it says page not found could you provide the link?
Answer by YoungDeveloper · Jan 02, 2014 at 08:06 AM
I explain it very clearly here:
http://answers.unity3d.com/questions/550578/cant-understand-getcomponent-c.html
and here
http://answers.unity3d.com/questions/597617/how-do-i-addsubtract-variables-between-two-differe.html
hi thanks for the response I tried this : function Start(){ var script : IronCollection = IronCollection.GetComponent("Iron"); Debug.Log("Iron"); }
but now it says BCE0020: An instance of type 'UnityEngine.Component' is required to access non static member 'GetComponent'. I'm sorry I am very new to unity and scripting
Sort your code.
var something : ScriptName = gameObjectName.GetComponent("ScriptName");
something.variablesFromOtherScript = true;
If the script is located on the same gameobject, you can do just:
var something : ScriptName = GetComponent("ScriptName");
Better syntax:
var something : ScriptName = gameObjectName.GetComponent.<ScriptName>();
Yeah it is, but i better not touch that part if person is still a learner, I've said it numerous times, and almost each time answer was "isn't this c#?", and then again i had to explain that no it isn't.
Answer by tanoshimi · Jan 02, 2014 at 09:06 AM
The script reference is at http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Components.html
And simply swapping the names shown in the example there to your scenario gives:
var IronScript : NameOfTheScriptInWhichIronIsDefined;
IronScript = GetComponent("NameOfTheScriptInWhichIronIsDefined");
IronScript.Iron = 500f;