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.
I believe you can also do function get and function set to enable properties. Functions can return values, they don't just have to be void like the ones I show here.
– whydoidoitThey are used less in Unity as the composition model of multiple scripts on a single object provides a similar implementation pattern with the ability to inherit the actual values. However, they do provide very useful functionality if you use them for things like spells, objects etc. It allows you to treat multiple scripts without needing to know which one you have. In general interfaces are more flexible than inheritance (you can have multiple of them on a single object) but you need to code the implementation each time.
– whydoidoitInteresting. I'll give this a shot. I may just use inheritance for the stats and this Interface model for the functions. Again, thank you very much!
– steezideez