Add button to Unity3d editor
Asked Answered
A

2

5

In Unity3D, I can have a property field appear in the editor by simply adding a public property to the class. Is it possible to add a button next to this field that opens up a file browser that populates that field?

I've found EditorUtility.OpenFilePanel but how can I add a button to call that method within the editor? (I don't mean a menu in the toolbar at the top as shown in the example code on that page)

Thanks

Appreciable answered 14/5, 2016 at 22:32 Comment(0)
K
10

The GUILayout.Button() method displays a button in the inspector when you select the gameObject which are you referencing.

For example... this code (customButton.cs) adds a button to the inspector in the script "OpenFileButtonScript.cs" which calls its OpenDialog() method.

using UnityEngine;
using System.Collections;
using UnityEditor;

[CustomEditor(typeof(OpenFileButtonScript))]
public class customButton : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        OpenFileButtonScript myScript = (OpenFileButtonScript)target;
        if (GUILayout.Button("Open File"))
        {
            myScript.OpenDialog();
        }
    }

}

This is the "OpenFileButtonScript.cs" script:

using UnityEngine;
using System.Collections;
using UnityEditor;

public class OpenFileButtonScript : MonoBehaviour {

    public string path;

    public void OpenDialog()
    {
        path = EditorUtility.OpenFilePanel(
                    "Open file",
                    "",
                    "*");
    }
}

I hope this can help you. For more info about buttons see this videotutorial

Kendrick answered 14/5, 2016 at 23:45 Comment(0)
O
0

I've had this problem & created this asset to not only call methods, but also test the parameters directly from the inspector simply by adding [ProButton] before the method

https://assetstore.unity.com/packages/tools/utilities/inspector-button-pro-151474

enter image description here

Ochs answered 14/3, 2023 at 10:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.