Search Unity

Selection.activeGameObject not selecting project asset

Discussion in 'Scripting' started by Edvard-D, Jul 1, 2017.

  1. Edvard-D

    Edvard-D

    Joined:
    Jun 14, 2012
    Posts:
    129
    I have code in an editor script that runs when the object it's attached to is selected in the project asset hierarchy. This code clears out SerializedProperty array elements that are now empty after an object stored within them was deleted.

    Right now, after deleting an object I'm displaying a message reminding myself to click on the object with the editor script in question so the code can run and the array can get cleaned up. I'm detecting whether an object was deleted by using OnPostprocessAllAssets. What I'd like to do is have the script automatically select the correct project asset so that its inspector displays, causing the custom editor script to run and the array to get cleared out. It would save me from accidentally missing the reminder to click on that object myself.

    From what I've found, the way you're supposed to be able to do this is by setting Selection.activeGameObject. The code I'm using is below:

    Code (CSharp):
    1. var selectedObject = AssetDatabase.LoadAssetAtPath<GameObject>(mansionGenServicePath);
    2. Selection.activeGameObject = selectedObject;
    After setting this value I have a Debug.Log that's confirmed the value is set correctly. The problem is that the object is never actually getting selected, its inspector is never being displayed, and thus, the code to remove empty elements is never getting called.

    Have I misunderstood how you're supposed to go about something like this?

    EDIT: Got a response at this Reddit thread.
     
    Last edited: Jul 1, 2017