I try to build a library of game objects of instruments that will, later on, be used in many different configurations to animate and simulate simple Flash builds.
The instruments, being interactive, will have a variable that can be set from the Inspector as, e.g. FROM or TO or both, depending if the object only inputs, outputs or both.
I know the name of the game object but I don’t know the name of the script. How can I address that? The documentation writes about GetComponent but that requires to know the name of the script … unless I missed something.
Alternatively, I can call all the scripts for e.g. “script” and place them in different folders, together with the object, textures, etc. But, is it wise?
My question is essential as what I try to organize now is what I will have to work with for the years to come. I want the architecture to be correct now, before I end up with a lot of objects that need restructuring.
Thanks in advance,
There are many ways to go about this.
You can use Interfaces. If all your instrument scripts implement an
IInstrument interface you can reference them like that, without having to know their specific names.
Interfaces allow you to ensure the script you’re referencing has the defined behaviour and properties, such as input/output properties, and methods that are shared by all of your instruments, while each of them has it’s own implementation of the interface’s requirements.
Another way to go about it is with an Abstract Class. It’s very similar to an interface, with the major difference being your script can’t inherit from multiple abstract classes (note that Interfaces are implemented while abstract classes are inherited). From my experience they behave more nicely with Unity’s serialization and inspector than interfaces, so it’s a viable option.
Another way altogether is simply create a base class and have the scripts inherit from it and simply override it’s methods with an implementation of their own. This allows you to define default behaviour straight in the class definition stage and doesn’t force you to implement anything in the inherited classes, which is arguably worse practice than the previous options.
On another note, you may also want to take a look at Generics, another powerful feature of C# that comes in handy quite often.