Collect all renderers in game object

I’m trying to collect all of the renderers in a game object.

using System.Linq; 

      IList<Renderer> rendererList = new IList<Renderer>();

      foreach (Transform item in Container.transform)
      {
         If(item == Renderer)
            rendererLink.add(item)
      }

the ‘Contaner.transform’ isn’t recognized. Do I need to add a reference to System.Ling to the project in MonoDevelop? Hoe else could I accomplish this? Thanks.

You are heavily mixing up the different object types there, which is not going to work.

First of all - what is “Container”?
If that is just a simple gameObject, you could do somethink like this:

using System.Collection.Generics;

List<Renderer> rendererList = new List<Renderer>();
GameObject container;

void Start() {
	GetRenderers();
}

void GetRenderers() {
	foreach (Renderer objectRenderer in container.GetComponentsInChildren<Renderer>()) {
		rendererList.Add(objectRenderer);
	}
}

It’s important to use the System.Collections.Generic in this case as you are going for a plain list. Linq is not really necessary in this case.

Yet the most important part is to deal with the correct types and in your foreach loop also first search the correct types, then assign them as renderers.

If you want to stick to Linq use something like this:

using System.Collection.Generic;
using System.Linq;

List<Renderer> rendererList = new List<Renderer>();
GameObject container;

void Start() {
	GetRenderers();
}

void GetRenderers() {
	Renderer[] objectRenderers = container.GetComponentsInChildren<Renderer>();
	rendererList = objectRenderers.ToList<Renderer>();
}

Again, it’s important to stick to the right object types! And furthermore, IList is just an interface and cannot be used like that. You will definitely need to use System.Collections.Generic.

Yet, as GetComponentsInChildren<>() already returns an array you may already have gotten what you need and could possibly work with the resulted array rather than transforming that into another list.

1 Like