Search Unity

Question What is the correct way to create nested inspector using new UIElements?

Discussion in 'UI Toolkit' started by IndieForger, Nov 30, 2022.

  1. IndieForger

    IndieForger

    Joined:
    Dec 31, 2012
    Posts:
    92
    I am trying to create a custom inspector for the parent object for serialized list of scriptable objects.

    Goal of this exercise is to create an inspector allowing to edit scriptable object properties from the parent object inspector level (without switching the context to scriptable object itself).

    I have been looking at Editor.CreateEditor documentation trying to use it as a template. Example code uses legacy
    OnInspectorGUI()


    Below works totally fine.

    Code (CSharp):
    1. public override void OnInspectorGUI()
    2. {
    3.     Editor.CreateEditor((target as MyComponent).transform).OnInspectorGUI();
    4. }
    However, when I am trying to run it from
    CreateInspectorGUI()
    to make it work with UIElements it renders nothing. Trying to call CreateInspectorGUI on created editor to return VisualElement object.

    Code (CSharp):
    1. public override VisualElement CreateInspectorGUI()
    2. {
    3.     return Editor.CreateEditor((target as MyComponent).transform).CreateInspectorGUI();
    4. }
    Seems
    CreateInspectorGUI()
    is a virtual method returning null.

    Which method should I call to return VisualElement for given transform editor? Is that even possible?
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,930
  3. IndieForger

    IndieForger

    Joined:
    Dec 31, 2012
    Posts:
    92
    @spiney199 Thank you! It did the trick.

    Code (CSharp):
    1. public override VisualElement CreateInspectorGUI()
    2. {
    3.     return new InspectorElement(Editor.CreateEditor((target as MyComponent).transform));
    4. }
     
  4. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,930
    You don't need to create an editor. You should just be able to pass in any UnityEngine.Object and it will draw the inspector for it.
     
  5. IndieForger

    IndieForger

    Joined:
    Dec 31, 2012
    Posts:
    92
  6. lgarczyn

    lgarczyn

    Joined:
    Nov 23, 2014
    Posts:
    68
    Just to add to this, if anyone is trying to create a nested inspector for Materials:

    You need to call

    Code (CSharp):
    1. InternalEditorUtility.SetIsInspectorExpanded(myMaterial, true);
    Before creating and drawing the InspectorElement
     
    fxlange likes this.