Mathijs van Nimwegen
Mathijs van Nimwegen

Reputation: 11

Unity - How to react to scene picking? How to force select a parent by picking its child in the sceneview

I have the following situation I need an answer to: I have a parent object with children. These children all have unique meshes. Whenever these children are selected in the SceneView, the parent needs to be selected in stead. The children should never have their inspectors exposed (not even a fraction of a second).

How do I do this?

There are two possible solutions that I have come up with which are not the solution I wish to go for.

Is there an instant solution to this which can guarantee me the functionality of SelectionBase, but then every time in stead of only the first time I click it?

Thanks in advance! :)

Upvotes: 1

Views: 2555

Answers (1)

Mathijs van Nimwegen
Mathijs van Nimwegen

Reputation: 11

I have found a way to do exactly what i want. I combine the [SelectionBase] attribute with a piece of code in the editor OnSceneGui.

  • First add the [SelectionBase] attribute to your class

  • Second add this code to its editor class

      private void OnSceneGUI()
      {
          HandleUtility.AddDefaultControl(0);
    
          //Get the transform of the component with the selection base attribute
          Transform selectionBaseTransform = component.transform;
    
          //Detect mouse events
          if (Event.current.type == EventType.MouseDown)
          {
              //get picked object at mouse position
              GameObject pickedObject = HandleUtility.PickGameObject(Event.current.mousePosition, true);
    
              //If selected null or a non child of the component gameobject
              if (pickedObject == null || !pickedObject.transform.IsChildOf(selectionBaseTransform))
              {
                  //Set selection to the picked object
                  Selection.activeObject = pickedObject;
              }
          }
      }
    

This allows the first pick to select the component. From then on, only when you select non-child objects in the scene, selection will actually change.

Upvotes: 0

Related Questions