Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Generally more performant to attach scripts for interact-oriented mechanics to player or the object?

Discussion in 'Scripting' started by electricco20, May 2, 2020.

  1. electricco20

    electricco20

    Joined:
    Feb 21, 2020
    Posts:
    10
    Hello,

    Hopefully my title made some sort of sense.

    Essentially, I'm wondering if it's generally considered more performant to attach the scripts that handle object interactions like pushing/pulling or chest opening to the player or the door.

    Currently, I have these scripts attached to the player, which each fill an array on start, looking for objects tagged with their appropriate functions, such as "draggable", "openable", "drive-able" etc. Then, when the player comes in contact with one of these via raycast, I execute the functions needed to allow the player to click to drag the object, or open the chest etc.

    However, I'm wondering if it's better practice to instead attach these sorts of scripts to each instance of the objects themselves then have them activate when the player makes contact via a trigger collider or the player raycast or both. Just not sure if calling an array on start that could potentially fill with a lot of objects is a lesser evil than having multiple instances of the same script floating around (attached to each interact-able object).
     
  2. Alvarezmd90

    Alvarezmd90

    Joined:
    Jul 21, 2016
    Posts:
    151
    Hm not sure. In my project I have it the other way around like you describe. Most importantly is to take account for whether that particular instance has to take it's responsibility for a certain action or not. Tight-coupling is something to look out for and it's indeed a good practice to have these intractable classes derive from a base class in case you need an object to behave similarly but act differently depending on the type.
     
    electricco20 likes this.