- Home /
How to watch variables from another script efficiently?
Good evening!
unity 5.3.4, c#
How would I continuously watch a variable from another script in a very efficient manner?
Scenario/Example:
I have a HighLevelControllerScript class with a variable field
public GameObject checkThisObject;
I drag and drop my PlayerController GameObject into the checkThisObject field in the inspector.
The PlayerController has a script attached to it called PlayerManager.
Now, in that HighLevelControllerScript class's Update() I do a
Int lvlCheck = checkThisObject.getComponent<PlayerManager>().level;
Then run an if statement on that int to check if level == 20. If so... do something amazing... like get a daedric katana.
Psudo Code:
public class HighLevelControllerScript : MonoBehaviour {
//Set vars
public GameObject checkThisObject;
void Update(){
Int lvlCheck = checkThisObject.GetComponent<PlayerManager>().level;
if(lvlCheck == 20){
Debug.Log("You just received a new weapon... check your inventory");
}
}
}//End Class
Is that the best way to go about watching a variable from another script? Seems to me that would be really inefficient.
And coroutines, don't seem to be a good option.
Any help, provoking thoughts or points in the right direction would be greatly appreciated! Thank you!
Answer by Zodiarc · Oct 06, 2016 at 08:13 AM
https://en.wikipedia.org/wiki/Observer_pattern May be a step in the right direction. But is it really needed to do the check every frame? You could also implement some kind of notification system which notifies the HighLevelControllerScript when the player has leveled up.
I actually figured out a lot of different ways to go about what I wanted to achieve. I am still working on the best solution. But learning about delegates and states to achieve an event system gave me a whole different view on how to approach coding in unity better. Thank you for the advice.
Your answer
Follow this Question
Related Questions
Access Variables from another C# script on same object? 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Members not reset with SceneManager.LoadScene(scene); 0 Answers