Hi everybody,
i want to make a class hierarchy with monster (in 2D). All monsters have a different sprite, size, box collider, …
i have find in the web some explanation where the first object is a MonoBehaviour (AbstractMonster for example) and the other inherit of this one.
Now, if i want to instantiate a game object with the specific monster’s properties, what is the best practice to do something like that ?
i don’t want to make a prefab for each type of monster.
It’s entirely possible to instantiate from an object in the scene - it doesn’t have to be a prefab.
You’ll need to pass your monster GameObject as the first argument to Instantiate:
Create an empty GameObject, then add your Monster script to it as a component.
Give the new object a name (or tag), then you can refer to it from a script.
However, at this point you may as well turn the original monster into a prefab so it doesn’t clutter up the scene. You can still change the sprites, size etc from a script once you’ve instantiated a prefab.
It is possible to script the whole thing: i.e spawn an empty GameObject in a script, then create a new Monster component also in the script, and add it to the GameObject, but that’s pretty much what a prefab already does
You use a script called “monster initializer” or something, and make it have a public reference to a base-class you’ll be using to derive all of your monsters, for instance “monster”. You then give it some sort of an enum selection for which kind of monster you want to make. In the Awake function, have it instantiate a new GameObject as a child and use AddComponent to add a different class object that derives from “monster” (like “goblin”, “orc”, “harpy”, etc…) based on the enum you selected in the editor, which you’ll assign to your “monster” reference you made.
In the “monster” base class script (abstract), you’ll need to set up a function that resizes the GameObject, creates the collider and various other scripts, etc… You’ll also need to set up an “OnApplicationQuit” function that destroys its own GameObject when it exits so that you don’t accumulate more GameObjects. This would allow you to have many different monsters all instantiated from a single prefab, based on a selection, but you’ll have a unique sub-class of “monster” for every single monster in your game, which really isn’t all that different from having a bunch of different prefabs IMO.
A far better way would be to do much the same thing using a Scriptable Object class which you’ve used to create a “monster database”. Most of it would be the same, but you’ll be able to edit the details of each of your sub-classes in the editor without opening it in your text editor. There are some tutorials around for Scriptable Objects if you need them.