1
\$\begingroup\$

I am doing an infinite runner game and I want to be able to change the player vehicle during the game (I mean during the race by pushing a button).

I was thinking on destroying the previous player prefab and instantiating a new one for the new vehicle prefab, but this way the playercontroller script attached is deleted too.

So my question here is if this is the best way to do this and how could I keep the attached playercontroller.

\$\endgroup\$
2
\$\begingroup\$

My usual route is to separate the logical and visual parts of the game object:

  • Root of my prefab (contains control script(s), rigid body if applicable)

    • "Visual" child object (contains mesh renderer / sprites / etc)

Colliders can go either at the root, or in a child object separate from the visual child.

This way I can do anything I want to the underlying visual - squash & stretch it to juice up its movement animations, bounce it around, etc. - without impacting the physics simulation or gameplay logic.

It also means we can swap the visual without losing the player controller, by either destroying the old one and instantiating a new visual child object in its place, or by having all the visuals present at all times, but disabling the game object for all but one of them at a time, and just swapping which one is active.

The latter option is good if you cycle appearances between a small-ish set of options frequently, so you're not incurring extra instantiation/destruction overhead and memory allocation constantly. But if you have a very large roster of visuals and each playthrough will only see a few, it might not be more efficient to load them on demand.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thank you! I like your alternative. Since in this case there won't be a lot of vehicle options I'll try the latter option. \$\endgroup\$ – Hector Apr 9 at 14:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.