How to get an array of gameobjects that have a certain script attached to them?
Hi, I want to know how to get an array of gameobjects in my scene that have a certain script attached.
I am working on RTS style drag selection, which is working, but and i want to check against all objects with certain script not just with a certain tag.
void CheckObjects()
{
//get array of all selectable objects in game (this done once begining of game for performance
//create a vector for each that is the camera screen point note should only do this for rendered objects
foreach (GameObject selectable in selectables)
{
if(selectable.GetComponent<Renderer>().isVisible) //should use variable not getcomponet very frame
{
Vector3 camPos;
camPos = Camera.main.WorldToScreenPoint(selectable.transform.position);
camPos.y = CameraOperator.InvertMouseY(camPos.y);
if(selection.Contains(camPos))
{
selectable.GetComponent<Unit>().selected=true;
}
else
selectable.GetComponent<Unit>().selected=false;
}
}
}
So instead of : selectables = GameObject.FindGameObjectsWithTag("selectable");
some thing like selectable = FindObjectsOfType(typeof(unit)) as unit[]; ?
Answer by ComradeVanti · Mar 16, 2016 at 05:20 PM
Try something like this:
GameObject[] getObjects() {
Script[] scripts = FindObjectsOfType<Script> ();
GameObject[] objects = new GameObject[scripts.Length];
for (int i = 0; i < objects.Length; i++)
objects [i] = scripts [i].gameobject;
return objects;
}
Good luck :D
That works thank you very much Brullix.
Size not any ideas how you would improve that function so it accepts a string and could then find any script
Answer by andymerck · Mar 16, 2016 at 05:38 PM
ill try that, perhaps i am better off having a game manager that knows of all units?
Your answer
Follow this Question
Related Questions
How can I count the number of prefab clones? 0 Answers
Unity FindObjectsOfType ruining my performance? 0 Answers
C# find objects of type and store them in a array 0 Answers
FindObjectsOfType giving out null 1 Answer
How does FindObjectsOfType<> work? 1 Answer