- Home /
A more graceful way to get a list/array of a certain component from all GameObjects of a type?
I'm using FindObjectsOfType() to get an array of GameObjects that have a certain script attached. But what I really want is a list/array of the SpriteRenderer on each of those objects. I've tried different ways of casting without luck. Is there a more graceful way to do it than manually running through the array of objects and adding a reference to the SpriteRenderer of each one to a list?
Here's what I'm doing now, it seems ugly:
public class DefenderButton : MonoBehaviour
{
List<SpriteRenderer> allDefenderSRs = new List<SpriteRenderer>();
private void Start()
{
DefenderButton[] allDefenderButtons = FindObjectsOfType<DefenderButton>();
foreach (var item in allDefenderButtons)
{
allDefenderSRs.Add(item.GetComponent<SpriteRenderer>());
}
}
Answer by ShadyProductions · Jun 08, 2020 at 11:23 AM
Only thing you could do is reduce code lines with System.Linq.
private List<SpriteRenderer> allDefenderSRs;
private void Start()
{
allDefenderSRs = FindObjectsOfType<DefenderButton>()
.Select(a => a.GetComponent<SpriteRenderer>())
.ToList();
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613000345im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Cannot figure out how to find animation in animator by name. 0 Answers
What is the order of execution for the instantiated object's GetComponent.Script.DoSomething? 1 Answer
how do i use component gathered from ontriggerEnter, outside of that function? 1 Answer
,How to get the script of an element? or the GameObject of an Component? 1 Answer
Setting thrown object to kinematic after hitting target? 1 Answer