Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

C#: Check if a component was created with [RequireComponen (typeof (Type))]

Discussion in 'Editor & General Support' started by chees502, Jul 28, 2015.

  1. chees502

    chees502

    Joined:
    Jan 25, 2014
    Posts:
    22
    I am looping through, and evaluating all the components on GameObjects and I need to check to see if a component was added or dependent on [RequireComponen (typeof (Type))] from another component. I assume I will be needing to use some reflection to get at the attribute.

    There is 2 ways I see this happening. Check if the current component I am evaluating is required by another, or (less preferable, but understandably the more likely answer) check if the current component I am evaluating is requiring another component, and building a dependency list.
     
  2. Sickwitit

    Sickwitit

    Joined:
    Dec 22, 2014
    Posts:
    123
    Why not just create a simple ComponentManager that keeps track of all your created components and what happens to them?
     
  3. chees502

    chees502

    Joined:
    Jan 25, 2014
    Posts:
    22
    Because they are not Components within my control. Either from other team members, or even some Unity made components use the require.
     
  4. chees502

    chees502

    Joined:
    Jan 25, 2014
    Posts:
    22
    Sadly, I had to settle for the latter, but here is the code to check for required scripts
    Code (csharp):
    1.  
    2.   void CheckRequired(Type myType) {
    3.       Attribute[] attributes = Attribute.GetCustomAttributes(myType);
    4.       foreach (Attribute attribute in attributes)
    5.       {
    6.           if (attribute is RequireComponent)
    7.           {
    8.               RequireComponent req = (RequireComponent)attribute;
    9.               Debug.Log(req.m_Type0+" is required by "+myType);
    10.               RegisterRequired(myType, req.m_Type0);
    11.           }
    12.       }
    13.   }
    14.  
     
    Last edited: Jul 31, 2015
    Sickwitit likes this.