- Home /
Access a variable from another script in update function
I have a script that constantly checks if a bool is true or false, and a second script that does something. Now I want the second script to only do something when the bool is returned true. So on runtime I want script2 to constantly check if the bool in script1 is true, so something like this.
if(bool == true)
{
do;
}
what is the most efficient, most elegant way to do this? Thank you very much!
Answer by valyard · Jun 01, 2015 at 06:21 PM
I would do it this way.
In Script1 I would create an event like this:
public event EventHandler<object,EventArgs> SomethingHappened;
and when something happens, i.e. your bool value is set I'd fire this event
if (SomethingHappened != null) SomethingHappened(this, EventArgs.Empty);
In Script2 I would have a field referencing Script1 to subscribe to this event:
public Script1 MyScript;
void OnEnable()
{
if (MyScript) MyScript.SomethingHappened += onSomethingHappened;
}
void OnDisable()
{
if (MyScript) MyScript.SomethingHappened -= onSomethingHappened;
}
void onSomethingHappened(object sender, EventArgs e)
{
// do something
}
And set MyScript in inspector. This way you don't need loops, nor Script1 knows what other scripts are interested in something happening inside.
SomethingHappened and onSomethingHappened should have the same signature.
Hey, I managed to work it out before you answered :p and with fewer lines so I didn't take a closer look @ your code, but thank you so so much for your effort! you are amazing!