Search Unity

Resolved Is it better to destroy objects from their own script or the colliding script?

Discussion in 'Scripting' started by jmancoder, Nov 29, 2022.

  1. jmancoder

    jmancoder

    Joined:
    Feb 21, 2022
    Posts:
    3
    I am creating a simple brick breaker game. When a block is hit by the ball, it will play a sound effect, display a particle effect, and destroy itself. While it seems inefficient to instance the same script on so many block prefabs, I know it is also bad practice to modify another object directly. Thus, would it be better to perform these operations from the blocks or the ball?
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    In the end, it doesn't matter much, but...

    The reason I would have a script on the blocks might be because I want the blocks to have a health of their own, or maybe be invincible, or perhaps respond differently if I had different types of objects/balls that could hit it.

    Then you could simply pass over "Hey, object x hit you." and then let the block decide what it should do.

    Plus, I'd probably have this script handling other stuff like the color of the block. Maybe point values or something. It just allows for a bit of flexibility.

    But, that would just be how I'd do it, probably even if I had a simple block always gets destroyed setup.

    If your blocks are a prefab and you are instantiating them, there is nothing wrong with them having a script on them that handles stuff.
     
  3. TzuriTeshuba

    TzuriTeshuba

    Joined:
    Aug 6, 2019
    Posts:
    185
    I would probably have the logic on the Brick object. In addition to the reasons Brathnann provided, Simply Destroying an object is usually a placeholder, and special fx will eventually be added and possibly event triggering. For example, you may want a particle explosion before calling Destroy, or a slow fade or shrink effect on the brick, or animate its color or create a crack on the brick.
    your intuition of having a lot of bricks as compared to a single ball is definitely healthy though.