Search Unity

My Own Component Select Button.

Discussion in 'Testing & Automation' started by bilalincid7, Jun 21, 2022.

  1. bilalincid7

    bilalincid7

    Joined:
    Apr 9, 2021
    Posts:
    5
    I made my own Component selection button with Search Window. With Reflection, I add all the objects inherited from the Component class in the file to the Search Window. But I ran into trouble. For example, the Line Renderer class does not inherit directly from the Component class. It inherits from the Component class via the Renderer class. I scanned it with Reflection.as for the dll files, they all stand together, and I'm just checking Dec the class I'm scanning is inherited from the Component class. As such, it adds the Renderer class to Searchwindow. This is just an example. At the same time, the EventSystem also adds Listener objects. How do I solve it?


    Sorry for bad english
     
  2. dynamicbutter

    dynamicbutter

    Joined:
    Jun 11, 2021
    Posts:
    63
    If I understand the problem correctly you need a way to find which classes are derived from the Component class that works with multiple levels of nesting. One way to solve this problem is using recursion, like the
    GetAllParents
    function below.

    Code (CSharp):
    1. using System.Collections.Generic;
    2. using NUnit.Framework;
    3. using UnityEngine;
    4. using UnityEngine.TestTools;
    5.  
    6. public class Functions
    7. {
    8.     public static void GetAllParents(List<System.Type> parents, System.Type type)
    9.     {
    10.         var baseType = type.BaseType;
    11.         if (baseType == null) {
    12.             return;
    13.         }
    14.         parents.Add(baseType);
    15.         GetAllParents(parents, baseType);
    16.     }
    17. }
    18.  
    19. public class Tests
    20. {
    21.     [Test]
    22.     public void ReflectionTest()
    23.     {
    24.         var parents = new List<System.Type>();
    25.         Functions.GetAllParents(parents, typeof(Renderer));
    26.         Assert.AreEqual(true, parents.Contains(typeof(Component)));
    27.         parents.Clear();
    28.         Functions.GetAllParents(parents, typeof(LineRenderer));
    29.         Assert.AreEqual(true, parents.Contains(typeof(Component)));
    30.     }
    31. }
    32.  
    When using recursion heavily just be aware if the language you are using supports tail recursion to avoid stack overflows. In the case of c# it unfortunately does not support tail recursion, but in this particular case we should be ok since the amount of recursion will be small.