- Home /
How can I create an inspector that lets me select another script's variable.
Say my game has several stats like health, hunger, and thirst.
I want to create a prefab "stat bar" UI object with a generic script that has a "variable to watch" property, so I can just select the player object and the property in the inspector when I create a new UI component.
This inspector already exists but I can't figure out how to create the inspector element or how I'd even use it (see image attachment).
Answer by jdean300 · Dec 31, 2017 at 02:38 AM
That is not what that inspector is doing. The inspector in that image is allowing you to select a function to call whenever the value of the slider changes.
You can't really make something generic for what you want to accomplish... Maybe with a ton of work and some complicated code (and probably the use of reflection), but the closest I can think of that is reasonable is to start with an abstract class like the following:
public abstract class StatBehaviour : MonoBehaviour {
public abstract int GetStat(string statName);
}
And then in every behaviour that has stats, inherit from this class instead of MonoBehaviour and override this method. Example:
public class Player : StatBehaviour {
public int Health;
// ... other stats and such
public override int GetStat(string statName) {
if (statName == "Health") return Health;
return 0;
}
// ... other Player class stuff
}
Your StatBar script could then have two fields: one for the StatBehaviour to watch and one for the name of the stat to look at.
Note: A good improvement to make to this simple system is to create a Stat enumeration so that you don't use hard-coded strings.
Understood, thank you. That inspector does let you set properties as well, so I assumed I could use something similar to get their values.