How to make Lists (and Arrays) only take GameObjects of a certain "type"

If I were coding in generic C# I can create a list that only stores a certain type of object. If I accidentally try to add anything other than that type to the list I will be promptly told and can fix the problem quickly.

List<Foo> my_list = new List<Foo>();
my_list.Add(Bar) //Error - this is what I want to happen

However because I’m using Unity my script needs to be attached to a GameObject, and that needs to be stored in the List.

List<GameObject> my_list = new List<GameObject>();
GameObject Foo = new GameObject; Foo.AddComponent<Foo>();
GameObject Bar = new GameObject; Bar.AddComponent<Bar>();
my_list.Add(Foo) //Fine
my_list.Add(Bar) //Works, but I don't want it to

I only want the list to store “Foo” GameObjects (GameObjects with the Foo component), however there is nothing to stop me accidentally storing any type of GameObject, which could (and already has) caused me hours scratching my head trying to debug the problem.

Is there a way to subtype a GameObject so that it has the effect of List<GameObject(Foo)> my_list?

I don't know, so I'm approving the question. As a personal recommendation, I'd strongly urge you to use C# exclusively.

1 Answer

1

Oh wait. I was in a hurry last night and totally misunderstood the question. I thought you were using .js

Just make a list whose type is the component you want to store. You can safely add these components (and no other types of components) to that list. You can quickly cast between the component and the gameobject it lies on as-needed.

What you’re adding to the list is the actual Foo component, but because the Foo component is always on a gameobject, it’s always possible for them to have a two-way relationship.

List<Foo> myFoos = new List<Foo>();
Foo thisParticularFoo = myGameObject.GetComponent<Foo>() as Foo;
myFoos.Add( thisParticularFoo );
myFoos[0].gameObject // equates to "myGameObject"

This is the standard procedure to accomplish what you’re asking for. There are, of course, alternatives, but this is probably the most expedient approach. The only real catch here is that if you destroy the gameobject, the corresponding list element (its component) will become null, so you’ll have to watch out for that. Sorry for the confusion, I was clearing out the mod queue in a hurry.