- Home /
Noob c# question
How do you call variables from other scripts?
Just as an example:
If I had a variable called Vitality in a CharacterStatsScript, how would I call that variable to do something like... Health + Vitality*2 in a script called PlayerHealthScript.
Comment
Best Answer
Answer by spraycanmansam · Mar 13, 2014 at 01:15 AM
There's many ways, but the simplest would be to cache a reference to your CharacterStatsScript in your PlayerHealthScript. Something like this will work, assuming both scripts are attached to the same player game object ---
public class PlayerHealthScript() : MonoBehaviour
{
private CharacterStatsScript _myCharacterStats; // Cache variable
private int _health = 100;
private void Start()
{
// Get your CharacterStats component and store it in your _myCharacterStats
// variable for later use..
_myCharacterStats = this.GetComponent<CharacterStatsScript>();
// You can then access your character stats from your cached
// CharacterStats component anywhere in your script..
int totalHealth = _myCharacterStats.vitality + _health * 2;
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Call a method whenever the assigned variable gets altered 2 Answers
How to call Variable across scripts. 2 Answers