- Home /
Using getcomponent with an array
I have a line of code that finds all the vehicles in my scene:
vehicles = GameObject.FindGameObjectsWithTag ("Vehicle");
but I have to reference each vehicle so the controls can be shut off:
aeroPlaneControls = vehicles [0].GetComponent<AeroplaneUserControl4Axis> ();
is there a way I can reference all vehicles in the scene without typing the above code for every vehicle?
Answer by Tanshaydar · May 19, 2014 at 08:20 PM
GameObject[] Vehicles;
AeroplaneUserControl4Axis[] aeroPlaneControls;
vehicles = GameObject.FindGameObjectsWithTag ("Vehicle");
aeroPlaneControls = new AeroplaneUserControl4Axis[vehicles.Length];
for(int i = 0; i < vehicles.Length; i++){
aeroPlaneControls[i] = vehicles[i].GetComponent<AeroplaneUserControl4Axis> ();
}
Answer by himanshugupta159 · Jun 18, 2018 at 10:10 AM
It will be easy if you use getcomponents<> instead of getcomponent Check the Blogg related to it.LinK Below: link text
Your answer
Follow this Question
Related Questions
Find GameObjects with a true boolean and put them in an array? 1 Answer
Creating a single-line function for GameObject.Find and GetComponent (for multiple components) 3 Answers
C# SetActive GameObject Array 2 Answers
GameObjects static array NullReferenceException 1 Answer
C# GetComponent Issue 2 Answers