How to know if something is selected in Hierarchy or in project.

To be more specific.

I have made a prefab. Now that prefab naturaly resides in the “Project”, as well as it can be in a level’s “Hierarchy”. How can I know if what is selected and as such displays in the “Inspector”, is a prefab selected in project or something selected in the scene’s hierarchy,(and then (for example) do stuff in my OnInspectorGUI() to display different GUI depending on the situation).

Thanks

AssetDatabase.Contains( Object ) → true if it’s in the project, false if it’s in the scene.

For whoever stumbles upon this and looking specifically for gameobjects:

test for

gameObject.scene.IsValid()

if will return false when in project window

if(!gameObject.scene.IsValid())
{
     //true if the go is in a scene
     //false if is in project window
}

I recently ran in to the very same issue and found this question. I although figure you have solved it by now as the question was written a while ago - but for anyone stumbling into this question here’s a possible solution. What did it for me was to use PrefabUtility.

if (PrefabUtility.GetPrefabType(target)==PrefabType.None)
    // In Hieararchy
else
    // In Project View

This is not the absolute perfect solution, but I found it to be a little more settling than the others in this post. I noticed that objects have hideflags on them that govern where they are visible in the editor. I found out that when you use Resources.FindObjectsOfTypeAll<>() to locate components (Resources.FindObjectsOfTypeAll includes disabled components as well as ones on disabled GameObjects), any objects in the project window will come with the HideInInspector hideflag set on it and the ones in the hierarchy come with No hideflags. I don’t know enough about the internal operations of Unity to determine the accuracy of this fix, but it seems to be working flawlessly for me.

Here is an example:

public T[] FindObjectsOfTypeIncludingDisabled<T>() where T : Component
{
    T[] components = Resources.FindObjectsOfTypeAll<T>();
    if (components.Length == 0)
    {
        return new T[0];
    }

    List<T> allComponents = new List<T>();
    for (int i = 0; i < components.Length; i++)
    {
        T currentComponent = components*;*

if (currentComponent.hideFlags != HideFlags.None)
{
continue;
}

allComponents.Add(currentComponent);
}

return allComponents.ToArray();
}

I’m not sure if this is the perfect way, but if Selection.transforms.Length == 0, it is selected in Project.