- Home /
How do I change a variable in one script from a second script?
How do I change a variable in one script from a second script?
I have a script named ScriptOne attached to one object, and it has the following variable
var work : boolean = false
To change that variable from a script named ScriptTwo attached to another object, I thought I would just need to type into ScriptOne
GetComponent (ScriptOne.work) = true;
This doesn't seem to work, so what is the actual format?
Answer by Mike 3 · Jul 24, 2010 at 01:16 PM
GetComponent(ScriptOne).work = true;
Although, since your script is on another object, it's a bit more work
You'll need to get the gamebject by tag or name (unless you have an inspector assigned link to it)
Something like this:
var go = GameObject.Find("YourObjectsName");
go.GetComponent(ScriptOne).work = true;
Or this:
var go = GameObject.FindWithTag("YourObjectsTag");
go.GetComponent(ScriptOne).work = true;
Hi. Thanks for this.
On ScriptTwo I've added the following var:
var go = GameObject.Find ("ScriptOne");
and I've added the following line of code:
go.GetComponent(ScriptOne).work = true;
What I get is the following error message:
UnityException: You are not allowed to call this function when declaring a variable. $$anonymous$$ove it to the line after without a variable declaration.
Both of those lines will need to go into a function (e.g. Start)
Hey mike, I asked a similiar question and ashkan answered it but he never answered my comment... how can you find the most recently instantiated prefab and set the components variable to something (if possible)?
Your answer
![](https://koobas.hobune.stream/wayback/20220613065540im_/https://answers.unity.com/themes/thub/images/avi.jpg)