Created
August 6, 2020 09:49
-
-
Save AnsisMalins/c56a4f02120830937c7e4b72df6c7e7b to your computer and use it in GitHub Desktop.
Unity editor inspector fields to browse for paths
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using UnityEditor; | |
using UnityEngine; | |
public static class PathGUI | |
{ | |
public static void OpenFileField(string label, ref string path) | |
{ | |
string directory = path; | |
PathField(label, ref path, () => EditorUtility.OpenFilePanel(label, directory, null)); | |
} | |
public static void OpenFolderField(string label, ref string path) | |
{ | |
string folder = path; | |
PathField(label, ref path, () => EditorUtility.OpenFolderPanel(label, folder, null)); | |
} | |
public static void SaveFileField(string label, ref string path) | |
{ | |
string directory; | |
string name; | |
try | |
{ | |
directory = Path.GetDirectoryName(path); | |
name = Path.GetFileName(path); | |
} | |
catch (ArgumentException) | |
{ | |
directory = path; | |
name = null; | |
} | |
PathField(label, ref path, () => EditorUtility.SaveFilePanel(label, directory, name, null)); | |
} | |
public static void SaveFolderField(string label, ref string path) | |
{ | |
string folder = path; | |
PathField(label, ref path, () => EditorUtility.SaveFolderPanel(label, folder, null)); | |
} | |
private static void PathField(string label, ref string path, Func<string> browse) | |
{ | |
GUILayout.BeginHorizontal(); | |
GUILayout.Label(label, EditorStyles.label, GUILayout.Width(EditorGUIUtility.labelWidth - 1), | |
GUILayout.Height(EditorGUIUtility.singleLineHeight)); | |
path = GUILayout.TextField(path); | |
if (GUILayout.Button("Browse...", GUILayout.ExpandWidth(false), | |
GUILayout.Height(EditorGUIUtility.singleLineHeight))) | |
{ | |
string newPath = browse(); | |
if (!string.IsNullOrEmpty(newPath)) | |
path = newPath; | |
} | |
GUILayout.EndHorizontal(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment