- Home /
Make Variables shared by several objects
public int ChessOn1, ChessOn2, ChessOn3, ChessOn4, ChessOn5, ChessOn6, ChessOn7, ChessOn8; // check whose chess is on position, 0 for red, 1 for blue;
void PosToPut(int curchess)
{
if (gameObject.transform.name.ToString() == "Chess (0)")
{
ChessOn1 = curchess;
} else if (gameObject.transform.name.ToString() == "Chess (1)")
{
ChessOn2 = curchess;
} else if (gameObject.transform.name.ToString() == "Chess (2)")
{
ChessOn3 = curchess;
} else if (gameObject.transform.name.ToString() == "Chess (3)")
{
ChessOn4 = curchess;
} else if (gameObject.transform.name.ToString() == "Chess (4)")
{
ChessOn5 = curchess;
} else if (gameObject.transform.name.ToString() == "Chess (5)")
{
ChessOn6 = curchess;
} else if (gameObject.transform.name.ToString() == "Chess (6)")
{
ChessOn7 = curchess;
} else if (gameObject.transform.name.ToString() == "Chess (7)")
{
ChessOn8 = curchess;
}
}
Hey, buddy, new bee need help here, please.
i have nine gameobject chess(0) - (8), and nine variables ChessOn1 - 9. ChessOn1 - 9 are initialized as 0, and it is changed when the object is clicked. it works fine in single gameobject, when i click it, its corresponding variable would change, but in other gameobjects the variables remain 0. i want the nine objects to share the changes in the variables, how should i do that ? thx in advanced!
Answer by toddisarockstar · Mar 07, 2017 at 11:05 PM
if you want variables everyone shares, you would start by putting those variables on a separate script and stick that script on an empty game object or the camera or somplace like that.
after that, this is how all your scripts get to your shared variables:
for for example lets say you named your new script "brain". and that script is on a gameobject named "henry".
public brain shared;
void Start () {
// this line goes on any other script that needs to
//access your shared variables
shared = GameObject.Find ("henry").GetComponent<brain>();
//now you can access your shared variables like this:
shared.somevariable=true;
if(shared.someothervariable=="whatever")
{do something}
}
the variables in your new shared script just need to say "public" when you declare them