UnityEditor的一些方法

本文汇总了Unity编辑器中的一系列实用技巧,包括自定义菜单项、资源管理和操作、场景视图控制等,帮助开发者提高工作效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编辑器最上排按钮

[MenuItem("Tools/Cleanup/删除多余shader")]
static void XXX()
{
	...
}

快速获取全部资源

AssetDatabase.GetAllAssetPaths();

通过路径获取guid

AssetDatabase.AssetPathToGUID(path);

显示进度条

EditorUtillty.DisplayProgressBar("sss", "sdasd", 0);
EditorUtillty.DisplayProgressBar("sss", "sdasd", 1);
EditorUtillty.ClearProgressBar();

打开目录

EditorUtillty.RevealInFinder(path);

查找相关资源引用

[MenuItem("Assets/Tool/查找shader引用的cg文件", false)]
public static void FindCg()
{
    UnityEngine.Object obj = Selection.activeObject;

    string path = AssetDatabase.GetAssetPath(obj);

    if (!path.Contains(".shader"))
        return;

    var paths = AssetDatabase.GetAllAssetPaths();

    var list = new List<string>();

    foreach (var assetPath in paths)
    {
        if (assetPath.EndsWith(".cginc"))
        {
            list.Add(assetPath);
        }
    }

    string str = File.ReadAllText(path);
    var mathces = Regex.Matches(str, "#include\\s?\"(.*?)\"");

    var objList = new List<UnityEngine.Object>();
    foreach (Match item in mathces)
    {
        var r = item.Groups[1].Value;

        foreach (var cgincPath in list)
        {
            if (cgincPath.Contains(r))
            {
                Debug.Log(cgincPath);
                objList.Add(AssetDatabase.LoadMainAssetAtPath(cgincPath));
            }
        }
    }

    Selection.objects = objList.ToArray();
}

获取指定文件夹下指定文件

string selectedPath = AssetDatabase.GetAssetPath(Selection.activeObject);
DirectoryInfo direction = new DirectoryInfo(selectedPath);
FileInfo[] files = direction.GetFiles("*.prefab", SearchOption.AllDirectories);

foreach (var file in files)
{
    Debug.Log(file.FullName);
}

多选文件

// 多选
var gos = Selection.objects;

// 单选
Selection.activeObject

刷新并保存修改

AssetDatabase.Refresh();
AssetDatabase.SaveAssets();

保存文件(图片)

var assetPath = AssetDatabase.GetAssetPath(go);
Debug.Log(assetPath);
Texture2D tex = AssetDatabase.LoadAssetAtPath<Texture2D>(assetPath);
var b = tex2.EncodeToTGA();
File.WriteAllBytes(assetPath,b);

备份保存文件

[MenuItem("Assets/Tool/转换sdf", false)]
public static void ConvertSDF()
{
    var texSrc = Selection.objects[0] as Texture2D;
    
    var assetPath = AssetDatabase.GetAssetPath(texSrc);
    // Debug.Log(assetPath);
    
    Texture2D tex = AssetDatabase.LoadAssetAtPath<Texture2D>(assetPath);
    
    var fullPath = Path.GetFullPath(assetPath);
    var fileName = Path.GetFileName(assetPath);

    var fullPathWithoutName = fullPath.Replace(fileName, "");
    var newName = fileName.Replace(".png", "") + "_sdf.png";
    var newPath  = fullPathWithoutName + newName;
    
    RenderTexture rt = new RenderTexture(tex.width, tex.height, 0, RenderTextureFormat.ARGB32);
    Graphics.Blit(tex, rt);
    RenderTexture.active = rt;
    
    Texture2D texture2D = new Texture2D(tex.width, tex.height, TextureFormat.ARGB32, false);
    texture2D.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
    texture2D.Apply();

    var b = texture2D.EncodeToPNG();
    File.WriteAllBytes(newPath, b);
    
    AssetDatabase.Refresh();
}

快速复制物体

  
[MenuItem("GameObject/TTT/阵列100个")]
public static void InstanceGrid()
{
    UnityEngine.Object obj = Selection.activeObject;
    int row = 10;
    int space = 10;
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < row; j++)
        {
            var go = Instantiate(obj as GameObject);
            go.transform.position += go.transform.right * i * space + go.transform.forward * j * space;
            Undo.RegisterCreatedObjectUndo(go,"创建单个go : " + go.name);
            go.transform.name += $"_{i * row + j}";
        }
    }
 
}

设置scene view 的状态

SceneView.lastActiveSceneView.sceneViewState.fxEnabled = false;

检测Transform是否改变

void Update()
{
     if(transform.hasChanged)
     {
         UpdateInfo();
         transform.hasChanged = false;
     }
 }

Gizmo可以画线(包括Game UI)

public Vector3[] fourCorners =  new Vector3[4];
//.......
private void OnDrawGizmos()
{
  if(drawGizmosForDebugging)
  {
      Gizmos.color = Color.yellow;
      // _rectTransform.GetWorldCorners(fourCorners);
      // Rect r = new Rect
      // {
      //     x = fourCorners[0].x,
      //     y = fourCorners[1].y,
      //     width = fourCorners[2].x - fourCorners[1].x,
      //     height = fourCorners[0].y - fourCorners[1].y
      // };
      // Gizmos.DrawGUITexture(r, alphaTexture);
      for (int i = 0; i < 4; i++)
      {
          Gizmos.DrawLine(fourCorners[i], fourCorners[(i + 1) % 4]);
      }
  }
}

EditorWindow

搜吧

using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class ConvertURPLit : EditorWindow
{
    private static ConvertURPLit _myWindow;

    [MenuItem("Tools/ConvertURPLit", false, priority = 20)]
    static void Init()
    {
        _myWindow = (ConvertURPLit) EditorWindow.GetWindow(typeof(ConvertURPLit), false, "替换shader", true); //创建窗口
        _myWindow.Show(); //展示
    }

    void OnGUI()
    {
        GUILayout.BeginVertical();

        //绘制标题
        GUILayout.Space(10);
        GUI.skin.label.fontSize = 24;
        GUI.skin.label.alignment = TextAnchor.MiddleCenter;
        GUILayout.Label("Bug Reporter");

        GUILayout.Box(new GUIContent("ssssss"));
        GUILayout.Label(  " 请在游戏未运行时点击!!!");

        //添加名为"Save Bug with Screenshot"按钮,用于调用SaveBugWithScreenshot() 函数
        if (GUILayout.Button("Save Bug With Screenshot"))
        {
        }
    }

}

在这里插入图片描述

撤销操作

 Undo.RecordObject(renderer.sharedMaterials[i], "shader ssss");

画颜色文本

https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/StyledText.html

Play退出时操作

#if UNITY_EDITOR
    [UnityEditor.InitializeOnLoadMethod]
    private static void InitializeOnEnterPlayMode()
    {
        UnityEditor.EditorApplication.playModeStateChanged += (state) =>
        {
            if (state == UnityEditor.PlayModeStateChange.ExitingPlayMode)
            {
				// TODO 
            }
        };
    }
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值