curv
1
If I have a class with a defined variable called ‘lives’ within it (startup class), how can I access it from another class. i.e.
public class FirstClass : MonoBehaviour {
int lives = 0;
...
}
public class SecondClass : MonoBehaviour {
...
lives--;
...
}
I’ve read about GetComponent etc but not sure if this is what I need…?
Many possibilities:
a) You add reference to ForstClass instance into second class. (lives needs to be public).
b) Make lives is public. Then in SecondClass you do:
targetGameObject.GetComponent<FirstClass>().lives--;
c) Lives is not public, but you made a function in FirstClass.
public void SubtractLife() {
lives--;
}
Then you can call the function:
targetGameObject.GetComponent<FirstClass>().SubtractLife();
or you can do:
targetGameObject.SendMessage("SubtractLife");