Change selection from editor script.

I have an editor script that instantiates a prefab when a GUI button is pressed. What I want is for this new prefab to be the selected object in the scene view. Here is my code:

var newLink = EditorUtility.InstantiatePrefab(NodePrefab) as GameObject;
newLink.transform.position = target.transform.position;
//Change selection to newLink here

I thought I could do:

Selection.transforms = newLink.transform;

But selection is read only. How do I do this?

2 Likes

bump

Selection isn’t read-only, you just weren’t using a valid value for Selection.transform. That property is of type Transform[ ], not Transform. You may need to use activeTransform or gameObjects instead of transforms, too, to get the right effect.

Selection.transforms/Selection.gameObjects is read only. Selection.activeGameObject works, but there doesn’t seem to be any way to select multiple objects at once.

It is indeed read-only:

Property or indexer `UnityEditor.Selection.transforms' cannot be assigned to (it is read only)

Selection.objects, however, is not. This worked for me

[MenuItem("KVS/Selection Test")]

	static void SelectionTest(){

		GameObject transformOne = new GameObject("ONE");

		GameObject transformTwo = new GameObject("TWO");

		GameObject transformThree = new GameObject("THREE");

		

		GameObject[] newSelection = new GameObject[3];

		newSelection[0] = transformOne;

		newSelection[1] = transformTwo;

		newSelection[2] = transformThree;

		

		Selection.objects = newSelection;

	}

It properly created, and then selected, the three objects.

EDIT: Ignore the naming convention of the variables, I was too lazy to rename them after verifying Selection.transforms was read-only :smile:

8 Likes

Thanks for solving that mystery

Great success ~

Thanks, I was working along these lines myself and didn’t realize I could just take the array I had casted and place it into Selection.objects.
Very useful indeed.

Thanks,luckily I see it before writing my code

@KyleStaves nice snippet!

I wasn’t able to get this to work :frowning: am I missing something?

GameObject[] newSelection = new GameObject[transformArray.Length];

for(int i=0; i<newSelection.Length; i++)
{
          newSelection[i] = transformArray[i].gameObject;
}

Selection.objects = newSelection;

EDIT

Apparently, this DOES work. just had to restart Unity :roll_eyes:

1 Like