how to find all objects with certain script attached to it

I have a scene with lots of game objects. I wana find objects which has script named controller attached to it.
Anyway to do it?

3 Likes

open the scene you want to search.
find the ā€˜controllerā€™ script in your scripts folder, if you right click that script and select ā€˜find references in sceneā€™ this will show/filter all the gameobjects that are currently in your heirarchy that has this script attached.

if any objects are instantiated at runtime, then you will have to play then pause, and do the same search to find them.

25 Likes

No i wana do this in the game.
Heres my code

public Controller sf;
// Use this for initialization
void Start () {

sf= (Controller) GameObject.FindObjectOfType (typeof(Controller));

Debug.Log(sf);

This seems to find 2nd object in heirarchy which has controller script. How do i find 1st object in heirarchy with script.

Ah sorry.
not sure, i always assumed heirarchy order wasnt relavent unless dealing with render order of the new UI Canvas.

i just done this to find all entries and display their gameobject names, ill paste it in seen as ive done it now :slight_smile:

  Controller[] myItems = FindObjectsOfType(typeof(Controller)) as Controller[];
            Debug.Log ("Found " + myItems.Length + " instances with this script attached");
            foreach(Controller item in myItems)
            {
                Debug.Log(item.gameObject.name);
            }
5 Likes

This isnā€™t working for me. Iā€™m getting an error because a script that does not belong in this scene appears to be attached to an object in the scene. Thereā€™s no error to fix in the script, it just shouldnā€™t be there. I cannot find the object the incorrect script is attached to. When I do ā€˜find references in scene,ā€™ it shows hundreds of objects, most of which have no script attached, and none of which have the script Iā€™m looking for. How can I find the object in the scene that has the script thatā€™s causing the error?

3 Likes

Any solutions to this? I have a script in game but no clue as to where I put it. right clicking and ā€œfind referencesā€ is totally useless as it shows pretty much everything I have in the game. tried commenting out code to ā€œbreakā€ it because sometimes unity - when you click on the error - highlights the gameobject with the script

nevermind, monkeyed with your scripts to find it. works although no clue as to why. found the gameobject. mesh renderer off so going to change that so I can find it again
public class FindScript : MonoBehaviour {
public MonoBehaviour sf;
// Use this for initialization
void Start () {

sf= (MonoBehaviour) GameObject.FindObjectOfType (typeof(autoSpawn));

Debug.Log(sf);
}
}