Skip to content

Scripts: Requirements & Placement

antfarmar edited this page Dec 5, 2015 · 10 revisions

How to determine which objects get their own behavioural scripts?

Example Problem:

Does a Bullet require it's own script, or should the ShipShooter script handle them?

  • Bullets originate from the ship's firing script.
  • Should the ship then be responsible for repooling them after collisions or their lifetime expiry?
    • Ususally done with a delayed Invoke or Coroutine.
  • What happens if the ship is deactivated?
  • How are timed Invoke/Repeating & Coroutines handled when deactivating objects?

Solution:

One way to determine this is that if the behaviour of an object, however simple, is completely independent of another object (even those that are producing or require them), then write a separate Monobehavior script for them. This overcomes many problems(e.g. deactivations) that would occur if they were statically coupled in the same script.

For instance, if we deactivate the ship, then all of its scripts will become deactivated. This may seem desirable, but if the ship is killed (then deactivated), then bullets that have already been fired and are still active in mid-flight will be in limbo and not pooled (if only using coroutines?). We could still pool them mid-flight (right before ship deactivation), but that is not the desired behaviour for bullets. They have their own separately defined lifetimes. Bullets then should have their own behavioural scripts.

Also, having separate scripts for (even tightly-coupled) objects could also potentially prevent many unforeseen difficulties as the project grows in size/complexity.

Side Note: Be mindful of Parent-Child Transform relationships when activating/deactivating game objects: Deactivating parents also deactivate children!