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

'RequireComponent' equivalent for child objects?

Discussion in 'Scripting' started by Rxanadu, Mar 30, 2014.

  1. Rxanadu

    Rxanadu

    Joined:
    May 24, 2012
    Posts:
    50
    I was wondering if there was a way to set required components for child objects without creating a separate script and setting it up via '[RequireComponent(typeof())]'. I've been looking for a way to do this for ages, and I assume it's not possible to do it the way I intended. However, I just wanted to make sure.
     
  2. AL0932

    AL0932

    Joined:
    Mar 29, 2013
    Posts:
    22
    Anyone have an answer to this? I'm running into the same issue.
     
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    You'd probably have to do it manually. Search your GameObjects for the component and throw an error or create it if its not there. If you do it on a base class you can save having to code it for every component.

    You could tie into one of the messages, perhaps OnTransformChildrenChanged or OnValidate. There may also be an option with editor scripting.
     
    TonyLi likes this.
  4. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    12,670
    Like BoredMormon writes, just add an OnValidate() method to your parent GameObject's script. In the method, search for the required child GameObjects and/or scripts, creating them if they don't exist.