IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 游戏开发 -> Unity 从Inspector界面打开资源管理器选择并记录文件路径 -> 正文阅读

[游戏开发]Unity 从Inspector界面打开资源管理器选择并记录文件路径

一个小功能的实现历程


在AvProVideo插件中有个功能,点击视频组件中的按钮可以打开资源管理器窗口,找到目标视频资源并记录下资源路径。
查了一下实现起来并不难,主要有两点
一个是unity 自带的用于打开资源管理器的方法

EditorUtility.OpenFilePanel();

第二个就是自定义编辑器的操作

实现过程

阶段一:

脚本1:定义窗口、打开资源管理器

using UnityEngine;
using UnityEditor;

public class Example : EditorWindow
{
    static GameObject _objectBuilderScript;
    //[MenuItem("SKFramework/Example")]
    public static void Open(GameObject objectBuilderScript)
    {
        GetWindow<Example>().Show();
        _objectBuilderScript = objectBuilderScript;
    }

    
    private string path;

    private void OnGUI()
    {
        //水平布局
        GUILayout.BeginHorizontal();
        {
            GUILayout.Label("路径", GUILayout.Width(50f));
            path = GUILayout.TextField(path);
            if (GUILayout.Button("浏览", GUILayout.Width(50f)))
            {
            	//不用上边这个弹窗也可以
                path = EditorUtility.OpenFilePanel("成功啦 ?☉□☉?", Application.dataPath, "png");
                _objectBuilderScript.GetComponent<ObjectBuilderScript>().path = path;
            }
        }
        GUILayout.EndHorizontal();
    }
}

脚本2:操作类

using UnityEditor;
using UnityEngine;
public class ObjectBuilderScript : MonoBehaviour
{
    public  string path;
    
    public void BuildObject()
    {
        Example.Open(gameObject);
    }   
}

脚本3:重写Inspector界面
这个脚本要放在 Assets/Editor 文件夹下

using UnityEngine;
using UnityEditor;
using System;
[CustomEditor(typeof(ObjectBuilderScript))]
public class ObjectBuilderEditor : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        ObjectBuilderScript myScript = (ObjectBuilderScript)target;
        if (GUILayout.Button("选择图片资源"))
        {            

            myScript.BuildObject();
        }
    }
}

可以看到我们定义了一个按钮
在这里插入图片描述
点击后出现弹窗
在这里插入图片描述
点击浏览打开资源管理器
在这里插入图片描述

选择文件后可以看到路径被保存下来了
在这里插入图片描述

阶段二:

经过测试和实际应用,个人认为上述实现方式不够高效,因为需要多点一次弹窗内的浏览,遂做了一点点改动
脚本一:

using UnityEditor;
using UnityEngine;
using System;
public class ObjectBuilderScript : MonoBehaviour
{
    string  DefualtPath = Environment.CurrentDirectory+"/Resources/";
    
    public  string path;
    
    public void BuildObject()
    {
        string path1 = EditorUtility.OpenFilePanel("成功啦 ?☉□☉?", DefualtPath, "png");
        path = ReplacePath(path1);
        print(path);
    }

    public string ReplacePath(string FullPath)
    {
        string DPath = Environment.CurrentDirectory.Replace(@"\","/");
        string p = FullPath.Replace(DPath, "");       
        return p;
    }
}

脚本二:重写面板函数

using UnityEngine;
using UnityEditor;
using System;
[CustomEditor(typeof(ObjectBuilderScript))]
public class ObjectBuilderEditor : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        ObjectBuilderScript myScript = (ObjectBuilderScript)target;
        if (GUILayout.Button("选择图片资源"))
        {
            myScript.BuildObject();
        }
    }
}

点击Inspector中的选择按钮就可以直接打开指定目录啦

阶段三:

功能是有了,便捷度还不够
再改!

using System;
using UnityEngine;
using UnityEditor;
///增加了初始文件夹路径的选择
public class SetFilePath : MonoBehaviour
{
    public FileLocation fileLocation;
    string FilePath0 = "";

    [SerializeField]
    public string path;

    public void BuildObject()
    {
        FilePath0 = GetPath(fileLocation);
        string path1 = EditorUtility.OpenFilePanel("成功啦 ?☉□☉?", FilePath0, "png");
        path = ReplacePath(path1)==""?path: ReplacePath(path1);
        print(path);
    }

    public string ReplacePath(string FullPath)
    {
        //前半段
        string DPath = GetPath(fileLocation).Replace(@"\", "/");
        print(DPath);
        string p = FullPath.Replace(DPath, "");
        return p;
    }

    public string GetPath(FileLocation location)
    {
        string result = string.Empty;
        switch (location)
        {
            //case FileLocation.AbsolutePathOrURL:
            //    break;
            case FileLocation.RelativeToDataFolder:
                result = Application.dataPath;
                break;
            //case FileLocation.RelativeToPeristentDataFolder:
            //    result = Application.persistentDataPath;
            //    break;
            case FileLocation.RelativeToProjectFolder:
#if !UNITY_WINRT_8_1
                string path1 = "..";
#if UNITY_STANDALONE_OSX && !UNITY_EDITOR_OSX
                        path += "/..";
#endif
                result = System.IO.Path.GetFullPath(System.IO.Path.Combine(Application.dataPath, path1));
                result = result.Replace('\\', '/');
#endif
                break;
            case FileLocation.RelativeToStreamingAssetsFolder:
                result = Application.streamingAssetsPath;
                break;

            //default:
            //    result = path;
            //    break;
        }
        return result;
    }
}


public enum FileLocation
{
    //AbsolutePathOrURL,
    RelativeToProjectFolder,
    RelativeToStreamingAssetsFolder,
    RelativeToDataFolder
    //RelativeToPeristentDataFolder,
 
}
using UnityEngine;
using UnityEditor;
using System;
[CustomEditor(typeof(SetFilePath),true)]
public class ObjectBuilderEditor : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        SetFilePath myScript = (SetFilePath)target;
        if (GUILayout.Button("选择图片资源"))
        {
            myScript.BuildObject();
        }
    }
}

这样需要用到这个功能的对象直接继承SetFilePath就好啦

阶段四

功能测了测没问题,再加个贴心的小提示吧
在这里插入图片描述
在这里插入图片描述

using System;
using UnityEngine;
using UnityEditor;
namespace LAIALAIA
{
    public class SetFilePath : MonoBehaviour
    {
        public FileLocation fileLocation;
        string FilePath0 = "";
        public string path;

        public void BuildObject()
        {
            FilePath0 = GetPath(fileLocation);
            string path1 = EditorUtility.OpenFilePanel("成功啦 ?☉□☉?", FilePath0, "png");

            string path2 = "";

            if (string.IsNullOrEmpty(path1))
            {
                print("未选择");
                //return;
            }
            else
            {
                fileLocation = CheckFileLocationPath(path1);
                if (fileLocation != FileLocation.AbsolutePathOrURL)
                    path2 = ReplacePath(path1) == "" ? path : ReplacePath(path1); //只留后半段
                else
                    path2 = path1;
                path = path2;
            }
        }

        /// <summary>
        ///  Remove the default directory path from a path
        /// </summary>
        /// <param name="FullPath"></param>
        /// <returns></returns>
        private string ReplacePath(string FullPath)
        {
            //A directory
            string DPath = GetPath(fileLocation).Replace(@"\", "/");
            string p = FullPath.Replace(DPath, "");
            return p;
        }
        /// <summary>
        /// Check 默认路径是否准确
        /// </summary>
        private FileLocation CheckFileLocationPath(string FullPath)
        {
            FileLocation fLocation = FileLocation.AbsolutePathOrURL;
            foreach (FileLocation f in Enum.GetValues(typeof(FileLocation)))
            {
                fLocation = f;
                if (f != FileLocation.AbsolutePathOrURL)
                {
                    string gp = GetPath(f);
                    //是否包含 目标 路径
                    if (FullPath.Contains(gp)) break;
                    else fLocation = FileLocation.AbsolutePathOrURL;
                    //print(gp);
                }
            }
            //print("fileLocation:" + fileLocation);
            return fLocation;
        }

        /// <summary>
        /// Returns the corresponding segment A directory path based on the enumeration
        /// </summary>
        /// <param name="location"></param>
        /// <returns></returns>
        private static string GetPath(FileLocation location)
        {
            string result = string.Empty;
            switch (location)
            {
                case FileLocation.AbsolutePathOrURL:
                    break;
                case FileLocation.RelativeToDataFolder:
                    result = Application.dataPath;
                    break;
                //case FileLocation.RelativeToPeristentDataFolder:
                //    result = Application.persistentDataPath;
                //    break;
                case FileLocation.RelativeToProjectFolder:
#if !UNITY_WINRT_8_1
                    string path1 = "..";
#if UNITY_STANDALONE_OSX && !UNITY_EDITOR_OSX
                        path += "/..";
#endif
                    result = System.IO.Path.GetFullPath(System.IO.Path.Combine(Application.dataPath, path1));
                    result = result.Replace('\\', '/');
#endif
                    break;
                case FileLocation.RelativeToStreamingAssetsFolder:
                    result = Application.streamingAssetsPath;
                    break;

                    //default:
                    //    result = path;
                    //    break;
            }
            //print(result);
            return result;
        }

        /// <summary>
        /// Get Full Path
        /// </summary>
        /// <param name="path"></param>
        /// <param name="location"></param>
        /// <returns></returns>
        public string GetFilePath(string path, FileLocation location)
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(path))
            {
                switch (location)
                {
                    case FileLocation.AbsolutePathOrURL:
                        result = path;
                        break;
                    case FileLocation.RelativeToDataFolder:
                    case FileLocation.RelativeToProjectFolder:
                    case FileLocation.RelativeToStreamingAssetsFolder:
                        result = GetPath(location) + path;
                        //result = System.IO.Path.Combine(GetPath(location), path);
                        //print(result);
                        break;
                }
            }
            //print(result);
            return result;
        }
        /// <summary>
        /// Get the picture according to the path
        /// </summary>
        /// <param name="path"></param>
        /// <param name="location"></param>
        /// <returns></returns>
        public Sprite GetSprite()
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(path))
            {
                switch (fileLocation)
                {
                    case FileLocation.AbsolutePathOrURL:
                        result = path;
                        break;
                    case FileLocation.RelativeToDataFolder:
                    case FileLocation.RelativeToProjectFolder:
                    case FileLocation.RelativeToStreamingAssetsFolder:
                        result = GetPath(fileLocation) + path;
                        //result = System.IO.Path.Combine(GetPath(location), path);
                        //print(result);
                        break;
                }
            }
            Sprite sprite = TextureLoad.LoadOneImage(result);
            //print(result);
            return sprite;
        }

        private string GetStartFolder(string path, FileLocation fileLocation)
        {
            // Try to resolve based on file path + file location
            string result = GetFilePath(path, fileLocation);
            if (!string.IsNullOrEmpty(result))
            {
                if (System.IO.File.Exists(result))
                    result = System.IO.Path.GetDirectoryName(result);
            }

            if (!System.IO.Directory.Exists(result))
            {
                // Just resolve on file location
                result = GetPath(fileLocation);
            }
            if (string.IsNullOrEmpty(result))
            {
                // Fallback
                result = Application.streamingAssetsPath;//用默认的streamingAssetsPath
            }
            return result;
        }
    }


    public enum FileLocation
    {
        AbsolutePathOrURL,
        RelativeToStreamingAssetsFolder,
        RelativeToDataFolder,
        RelativeToProjectFolder
        //RelativeToPeristentDataFolder,
    }


    //using UnityEngine;
    //using UnityEditor;
    //using System;
    [CustomEditor(typeof(SetFilePath), true)]
    public class ObjectBuilderEditor : Editor
    {
        public override void OnInspectorGUI()
        {
            DrawDefaultInspector();
            SetFilePath myScript = (SetFilePath)target;
            if (GUILayout.Button("选择图片资源"))
                myScript.BuildObject();

            CheckPathIsTrue(myScript.GetFilePath(myScript.path, myScript.fileLocation));
        }
        /// <summary>
        /// Prompt control
        /// </summary>
        /// <param name="messageType"></param>
        /// <param name="message"></param>
        private static void ShowNoticeBox(MessageType messageType, string message)
        {
            GUI.backgroundColor = Color.blue;
            EditorGUILayout.HelpBox(message, messageType);

            switch (messageType)
            {
                case MessageType.Error:
                    GUI.color = Color.red;
                    message = "Error: " + message;
                    break;
                case MessageType.Info:
                    GUI.color = Color.green;
                    message = "Info " + message;
                    break;
            }
            //GUI.color = Color.yellow;
            GUILayout.TextArea(message);
            GUI.color = Color.white;
        }
        /// <summary>
        /// Checking path Correctness
        /// </summary>
        /// <param name="FullPath"></param>
        private static void CheckPathIsTrue(string FullPath)
        {
            //Debug.Log("FullPath" + FullPath);
            if (!System.IO.File.Exists(FullPath) || FullPath == string.Empty)//路径不存在
            {
                //Debug.Log("File not found:" + FullPath);
                ShowNoticeBox(MessageType.Error, "File not found:" + FullPath);
            }
            else
            {
                //Debug.Log("File path is normal." + FullPath);
                ShowNoticeBox(MessageType.Info, "File path is normal." + FullPath);
            }
        }
    }
}

完美~
在这里插入图片描述
参考文章:https://blog.csdn.net/qq_42139931/article/details/123206376
参考文章:https://wenku.baidu.com/view/1b41bac9561810a6f524ccbff121dd36a32dc422.html
官方文档:https://docs.unity3d.com/2018.4/Documentation/ScriptReference/EditorUtility.OpenFilePanel.html

  游戏开发 最新文章
6、英飞凌-AURIX-TC3XX: PWM实验之使用 GT
泛型自动装箱
CubeMax添加Rtthread操作系统 组件STM32F10
python多线程编程:如何优雅地关闭线程
数据类型隐式转换导致的阻塞
WebAPi实现多文件上传,并附带参数
from origin ‘null‘ has been blocked by
UE4 蓝图调用C++函数(附带项目工程)
Unity学习笔记(一)结构体的简单理解与应用
【Memory As a Programming Concept in C a
上一篇文章      下一篇文章      查看所有文章
加:2022-07-05 23:42:25  更:2022-07-05 23:42:28 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 10:31:54-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码