0

I have a base abstract class Component and a class GameObject with a list of Components. I want to retrieve a component from that list but I can't figure out how.

public T GetComponent<T>() {
    foreach (Component Component in Components) // Components is a list
       if (Component is T)
           return (T)(object)Component;

    return (T)(object)null;
}
imtouchk
  • 41
  • 1
  • 6

1 Answers1

1

Your code can be simplified using Linq to this line:

public T GetComponent<T>()
{
    return this.Components.OfType<T>().FirstOrDefault(); 
}

If that throws a NullReferenceException, then Components is null and you need to initialize it.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • It still throws a `NullReferenceException`, but `Components` is not null. The function stopped working since I started using Json.NET to save and load a `Scene` class which has all the GameObjects stored within – imtouchk Jan 11 '20 at 19:08
  • I guess you will need to use a debugger to solve that problem. See https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – nvoigt Jan 11 '20 at 19:39