Multiple Game Objects, different components

This is probably a really dumb question, but I’m completely stumped at this point. Here is the functionality I need to create:

  • Load multiple GameObjects, which have an attached script that has stat and
    function information.
  • Get data out of that attached script and then use it.

Now, I’ve been able to do this in a singular case via:

var Player1: GameObject;
function PrintDatas(){
 var p1Stats = Player1.GetComponent(MageScript);
 Debug.Log(p1Stats.Health);
}

Where I’m having issues, however, is if I want to use a different character - a Fighter for example. The fighter is unlikely to have the “MageScript” component, since that contains spells and stats for the Mage.

So, how would I access that script without being specific to the name? I tried substituting a string, but was not successful.

var statsString:String = Player1.name+"Script";

Resulting in the error: ‘Health’ is not a member of UnityEngine.Component’.

My other idea was to create a uniform “stats” script and save it as part of a prefab on the character game objects, but of course it’s the same script on each, so that doesn’t work for me - I need different functions and values.

Any help would be appreciated.

Sounds like you need an Interface or a base class that your other scripts inherit from.

Your problem with the string version of GetComponent is that neither you nor the compiler can cast it to a variable of the script you need.

If you have a base class with the common stats in it (inherited from MonoBehaviour) then you can inherit the other scripts from that rather than MonoBehaviour. Or you could use a common interface and implement it on all of your scripts. Or you could have separate scripts for each of the different stats and have all your characters implement the basic health ones.