Home > Blockchain >  gameObject.GetComponent<T> != null is always true. How?
gameObject.GetComponent<T> != null is always true. How?

Time:05-24

  1. I have a list of 3 game objects. Only ONE game object has a Light component attached.

  2. I'm iterating through the list of all game objects like this

      foreach (var eachGameObject in objs) //eachGamObject represents one of the three game objects in a list. 
    
  3. in foreach I'm checking eachGameObject if it has a T type component attached, like this

if(eachGameObject.GetComponent<T>() != null)

  1. "T" is a generic type. It can be any component. In my case I'm trying to find a GameObject with a Light component attached in the Scene.

The problem:

Even tho only ONE game object has a Light component attached, the "if" in point 3 always executes and its never NULL.

How? I'm always passing "Light" as "T" and obviously only ONE game object has Light component attached.

It's driving me crazy, any help much appriciated!

This is full function:

 public List<T> FindInScene<T>()
    {
        var objs = FindObjectsOfType<GameObject>();
        List<T> list = new List<T>();

        foreach (var eachGameObject in objs)
        {
            if (eachGameObject.GetComponent<T>() != null)
            {
                list.Add(eachGameObject.GetComponent<T>());
            }

        }

        return list;
    }

and in the same (Monobehaviour class) I'm testing it like this:

private void Start() { List lights = FindInScene(); Debug.Log(lights.Count); }

The "Count" is always 3 (equal to the game objects in the Scene).

CodePudding user response:

Check to see if this works:

private void Start()
{
    List<Light> lights = FindInScene<Light>();
    Debug.Log(lights.Count);
}

public List<T> FindInScene<T>()
{
    var objs = FindObjectsOfType<GameObject>();
    List<T> list = new List<T>();
    if(objs != null && objs.Length > 0)
    {
        for (int i = 0; i < objs.Length; i  )
        {
            if (objs[i].GetComponent<T>() != null)
            {
                list.Add(objs[i].GetComponent<T>());
            }
        }
    }
    return list;
}

CodePudding user response:

Try to Add where (generic type constraint),like this:

   public List<T> FindInScene<T>() where T :Component
    {
        var objs = FindObjectsOfType<GameObject>();
        List<T> list = new List<T>();
        foreach (var eachGameObject in objs)
        {
            if (eachGameObject.GetComponent<T>() != null)
            {
                list.Add(eachGameObject.GetComponent<T>());
            }

        }
        return list;
    }
  • Related