Interchangeable Objects/Prefabs

when needing things to be created into the game world I understand there are 2 options:

  1. instantiate, such as firing a gun to instantiate a bullet to destroy said bullet on impact.

  2. I know that one alternative to instantiating (as it can lead to memory fragmentation, and on mobile platforms is almost a bad joke) every time an object is to be created in the world is to find the maximum number of those things that “could” exist in your game, and then when they are needed get one that is not being used then reposition, reorient, and render it.

but at least in my mind this second approach only lends itself to be used with the same things.

for example: lets I have 3 types of bullets. the difference between the bullets will be that they each have a different child class of an abstract base class, and a different model. now all of these bullets have an equal likelihood to be created in the game, and therefore have an equal likelihood to be needed. I would like to use option2 above, but I would like to do it where I can interchange the model, and scripts. almost like interchanging the prefabs themselves.

Is this possible? How?

For the scripts specifically, by using inheritance you can maintain an array that is the maximum size which holds base class scripts. This array can hold any of the 3 child scripts as well. Perhaps this would also be the way to do what you’re talking about. Create an array to hold your max amount of game objects.

From my understanding of Unity, you can’t really do this with prefabs directly. An easier option (though costly in performance) would be to create the maximum amount of all 3 kinds of objects. Then no matter what, you would be able to have that many objects on the screen. However, I don’t think that a game studio would follow that methodology for bullets. I think that they instantiate a bullet when it is needed and delete it when it is no longer necessary. What is the lifetime of the bullets?