- Home /
Classes VS Variable Scripts
Hi, all! I make use of classes in some instances of my game and they are very useful. However, I am NOT using classes for my enemies for one simple reason:
I can't seem to figure how to get a new physical enemy prefab to spawn with the constructor and to have that tied to all of its respective class variables.
I am in full knowledge that classes will greatly enhance my game (especially when used with enemies!!)
If someone could point me in the right direction to be able to:
Spawn a physical enemy prefab in the constructor (I'm assuming the prefab would be a class variable)
Have that physical representation of the enemy be linked to its respective class instance
Thanks! - YA
No takers? :D I know this is possible. Otherwise game companies wouldn't be able to spawn such varied enemies sharing similar variable sets. This is practically what classes are meant for!
Answer by whydoidoit · Apr 23, 2013 at 06:52 AM
You don't have to make classes that standalone - you can make base classes that inherit from MonoBehaviour and then inherit your derived scripts from those. This is happening magically in your scripts anyway, but if you make it explicit then you can start to create your own class hierarchies.
That said - inheritance is only of minor use in Unity as it has a composition model where multiple scripts affect the same object. You can get more varied and robust combinations of enemies by varying the scripts attached to them.
This can be combined with interfaces for added performance (and a reduction of costly SendMessages).
The answer to this question: http://answers.unity3d.com/questions/15458/extending-from-interface-in-js.html talks about the definition of interfaces.
Basically you explicitly define your class rather than getting Unity to automagically create you one:
class YourScript extends MonoBehaviour implements ISomeInterfaceYouWrote
{
}
You can then inherit from your MonoBehaviour base class if it makes sense:
class AnotherScript extends YourScript
{
}
You shouldn't be trying to create prefabs in class constructors - it's just hard work and fighting the framework