Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Question null checking -- missed the empty object

Discussion in 'Scripting' started by zosichd, Sep 2, 2020.

  1. zosichd

    zosichd

    Joined:
    Jul 28, 2020
    Posts:
    2


    Code (CSharp):
    1. public static List<T> FindComponentsIn<T>(Transform inT, bool activeOnly = true, bool recursively = true) where T : class
    2.     {
    3.         List<T> res = new List<T>();
    4.         Transform ch;
    5.         T c;
    6.         for (int i = 0; i < inT.childCount; i++)
    7.         {
    8.             ch = inT.GetChild(i);
    9.             if (activeOnly && !ch.gameObject.activeSelf)
    10.                 continue;
    11.            
    12.             c = ch.GetComponent<T>();
    13.             if (c != null)
    14.                 res.Add(c);
    15.            
    16.             if (recursively)
    17.                 res.AddRange( FindComponentsIn<T>(ch, activeOnly) );
    18.         }
    19.         return res;
    20.     }
    ... this null - is some kind of some special like world ether?
    and if it somehow helping for understand, then the transferred T is a Collider
     

    Attached Files:

  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,947
    I think your collider is not null. It's just attached to a GameObject whose name is the string "null". Here's what my debugger looks like with an actual null component:

    upload_2020-9-2_17-37-6.png

    And here's what it looks like when I have a GameObject named "null":
    upload_2020-9-2_17-39-22.png

    Notice the quotes, the object type, and the dropdown arrow?
     
    Dextozz and zosichd like this.
  3. zosichd

    zosichd

    Joined:
    Jul 28, 2020
    Posts:
    2
    Yes, that's right, it's empty in quotes!

    But I didn't create an object named: null. Here is the hierarchy of objects, and here is this object that skips the check, and there are no components on it.


    Okay, this looks like the result of the internal work of the engine, where it is necessary to understand this null object as a result of a failure in the engine or outside ...

    I just adding:
    Code (CSharp):
    1.  if ( c != null && c.ToString() != "null")
    Thanks for the tip, the question is closed)
     

    Attached Files:

    Last edited: Sep 2, 2020
    PraetorBlue likes this.
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,947
    Yeah my explanation doesn't seem to completely add up because there is a Transform variable in your code
    ch
    which obviously is attached to the same object as the collider, and it's properly showing the name of the GameObject as "Legs". So something else weird is going on!
     
    zosichd likes this.