Get all instances of a prefab

I’m aware of Object.FindObjectsOfType, but as far as I know, it only finds built-in types (Material, RigidBody, etc). If not, how can I make to find all objects instances of my owm prefab?

I’m also aware of GameObject.FindGameObjectsWithTag, but I’m trying to find an alternative.

If it helps, I want to find it during Edit Mode.

Thanks!

Well, instances of prefabs have to be in the scene, so you will have to iterate through all objects and check them against your prefab reference. To get the prefab of an instance just use EditorUtility.GetPrefabParent() on your instance and you will get back a reference to the prefab asset.

This is the implementation of the “select” button inside the GameObjectInspector:

if (prefabType != PrefabType.MissingPrefabInstance && GUI.Button(position2, "Select", "MiniButtonLeft"))
{
    Selection.activeObject = EditorUtility.GetPrefabParent(base.target);
    EditorGUIUtility.PingObject(Selection.activeObject);
}

To check if an object in the scene is a prefab instance use EditorUtility.GetPrefabType().

Something like this should do:

// C# (not tested!)
List<GameObject> FindAllPrefabInstances(UnityEngine.Object myPrefab)
{
    List<GameObject> result = new List<GameObject>();
    GameObject[] allObjects = (GameObject[])FindObjectsOfType(typeof(GameObject));
    foreach(GameObject GO in allObjects)
    {
        if (EditorUtility.GetPrefabType(GO) == PrefabType.PrefabInstance)
        {
            UnityEngine.Object GO_prefab = EditorUtility.GetPrefabParent(GO);
            if (myPrefab == GO_prefab)
                result.Add(GO);
        }
    }
    return result;
}

Note that findObjectsOf Type will find ALL objects, also nested objects so you might end up with more than you’d expect. You might use EditorUtility.FindPrefabRoot if the prefab has nested objects to sort out the children of a prefab and to find the true root prefab.

Also take a look at the PrefabType since there are more than one possibilities. Choose what you need.

You can find prefabs, but prefabs of a certain type, not so much. One way is to put a particular script in your prefab, then look for all objects that contain that script, if tags aren’t cutting it for you.