- Home /
get same var from multiple different scripts
hi all
im trying to get to a var that placed in different scripts. for example: scriptA.js
state = true;
scriptB.js
state = true;
scriptMaster.js
gameObject.GetComponent(scriptA/B).state = false;
is it possible to get both "state" vars from scriptMaster.js with arrays and for loop in some way?
thank u R
Why not just have those two scripts reference the same object somewhere, and you can set the flag once?
yea u are right flavius i guess need to re Write my code
cheers
Answer by ageofchaos · Sep 09, 2013 at 07:24 PM
What you can do is create an abstract class that contains a protected bool "state" and have scriptA and scriptB inherit from it.
Here's one way to do it using C#:
public abstract class Statable : MonoBehaviour
{
public bool state;
}
public class ScriptA : Statable {}
public class ScriptB: Statable {}
public class ScriptMaster : MonoBehaviour
{
public void SomeFunction()
{
GetComponent<Statable>().state = false; //Gets any component that inherits Statable and sets its state to false
}
}
Note that in this example, you'll get a NullReference on ScriptMaster if there is no Statable attached to the same game object, and if there are multiple Statable scripts it will only set one of their states to false.
Thank for answering aoc Can i do it with js? Can u write an example of js code? C# is not my strong lang... Thanks
Please reply as a comment rather than posting an "answer" when replying to someobody's answer.
Your answer
Follow this Question
Related Questions
Accessing an Array in another function 1 Answer
Instantiated Prefab using its transform and object on other scripts 1 Answer
I'm having more problems accessing a variable from another script in c# 2 Answers
beginner question- several errors 1 Answer
Getting a Script without setting a variable to the script name 1 Answer