Project Prefab Design...

I’m hoping someone can help me figure out a proper way to configure my project (using Unity 2 free version).

Succinctly, I’m working on creating a multiplayer game with spaceships and I’m getting confused about the proper way to create my prefabs.

First, I want to have several different ships that a player can choose to be. So, for each different spaceship model, I create a prefab. Ex:

Ship_1

  • model

Ship_2

  • model

Then, I create a player prefab that contains a single ship and other prefabs as well. Ex:

Player

  • ship
  • close_cam
  • far_cam

The problem I am running into is that within the project hierarchy, I can’t add a “generic” ship under player. Of course I can add a ship via code but then I’m not sure what the point of the project hierarchy is since I’ll also have to set the targets of the close and far cam via code as well.

I think I’m either trying to do something that is impossible in Unity or I’m taking the completely wrong approach. I’m coming from an object oriented programming background and I guess I’m thinking that I should be able to create a Ship object and then extend that object into multiple different ships but maybe not…

Any help is appreciated.

Hm, not sure I understand. Are you looking for some sort of ‘prefab polymorphism’? If so, prefabs are concrete, not abstract; they’re ‘templates’ from which you can create multiple instances of a particular game object configuration.

If you want the player object to exist in advance but have the player choose a ship at run time, then adding the ‘ship’ object via code may in fact be what you’re looking for. Another option would be to have an entirely different player prefab for each ship, and instantiate the appropriate player prefab based on user selection.

In any case, for something like this there’s rarely one ‘right’ solution. If you need further advice, perhaps you could go into a bit more detail about what you’re trying to achieve.

Also, regarding the ‘object-oriented’ aspect, what it sounds like you’re describing (that is, a typical inheritance-based approach) is certainly possible. For example, you can create a base class that inherits from MonoBehaviour, and then derive other classes from that base class.

However, even though this approach can be useful in some cases, it shouldn’t be your go-to solution, IMO. Component-based systems are, generally speaking, designed to replace traditional inheritance-based systems, and in my opinion the component-based approach is to be preferred. To put it in practical terms, instead of thinking about how you can create a base ship class and derive other types of ships from it, think about how you could construct a particular type of ship by combining individual components such as energy source, thrusters, shielding, cargo unit, etc. (Either that, or just create a single ‘ship’ component with tweakable parameters exposed via the inspector.)