Search Unity

Question Hook into component constructors

Discussion in 'Scripting' started by Magnesium, Apr 13, 2021.

  1. Magnesium

    Magnesium

    Joined:
    Sep 14, 2014
    Posts:
    179
    Hello,

    I would like to know if it is somehow possible to hook on certain certain components when they are added to a gameObject. One usage is that i want the player to be able to disable 2d light if his machine can't handle a steady 60 fps with them on and it would be too costly to execute this in an update loop.

    If you have a better solution to this specific usage (there's little documentation about 2d lightning out there) you're welcome to share but i'll still be interested in an answer to the original problem :)

    Thanks
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,735
    No need to do it so early in the lifecycle, just do it after the scene is loaded.

    Besides you should ONLY interoperate against things in your own self during a "constructor"-ish time.

    The closest analogy is Awake(), which gets run on your behalf when AddComponent<T>() is called, either explicitly by you or when the scene / prefab is loaded into the scene. That's as close to a constructor as you can get, but like I said, ONLY do things in your own self, not on other things.

    The reason is, you don't even know if those other things have had their Awake() calls yet.
     
  3. Magnesium

    Magnesium

    Joined:
    Sep 14, 2014
    Posts:
    179
    I'm not sure i follow you, i think you're talking about the awake loop of an instantiated gameObject.

    What i would like to do, ideally, would be to extend some component classes and ad some hook in the construction sequence.

    Otherwise, catching every instantiated gameObjects Start function in a main script would work although it would be unnecessary in most cases.

    I already do a pass on scene start, but that doesn't account for objects created on the fly, and adding a custom script to each of them would be costly in term of maintainability.