找回密码
 立即注册
查看: 216|回复: 0

如何在Unity中将编号添加到对象?使用这个简单的技巧!

[复制链接]
发表于 2023-3-8 08:59 | 显示全部楼层 |阅读模式
在节点All_PathPoint_Parent下有多个子节点对象, 在unity编辑器模式中, 为每个子节点对象显示一个编号, 从1开始.

可以使用Editor GUI Utility在编辑器窗口中为对象绘制GUI。在All_PathPoint_Parent节点的子对象上循环,为每个子对象绘制GUI,显示其编号。下面是一个示例代码片段:
void OnSceneGUI()
{
    GameObject allPathPointParent = GameObject.Find("All_PathPoint_Parent");
    if (allPathPointParent != null)
    {
        Transform[] pathPoints = allPathPointParent.GetComponentsInChildren<Transform>();
        int count = 0;
        foreach (Transform pathPoint in pathPoints)
        {
            if (pathPoint == allPathPointParent.transform)
                continue;

            count++;

            Handles.Label(pathPoint.position, count.ToString());
        }
    }
}

这段代码可以放在Unity脚本(.cs)文件中。您可以将其添加到项目中的任何脚本文件中,只要它继承自MonoBehaviour或EditorWindow类,并确保脚本附加到场景中的对象上或打开Unity编辑器窗口。然后,将此脚本文件拖到场景中的任何对象上即可在编辑器模式下为对象显示编号。

如果在Unity中使用上述代码时找不到Handles,可能需要在脚本开头添加以下命名空间:
using UnityEditor;

以下是完整代码:
using UnityEditor;
using UnityEngine;

[ExecuteInEditMode]
public class DisplayNodeIndex : MonoBehaviour
{
    void OnSceneGUI()
    {
        GameObject allPathPointParent = GameObject.Find("All_PathPoint_Parent");
        if (allPathPointParent != null)
        {
            Transform[] pathPoints = allPathPointParent.GetComponentsInChildren<Transform>();
            int count = 0;
            foreach (Transform pathPoint in pathPoints)
            {
                if (pathPoint == allPathPointParent.transform)
                    continue;

                count++;

                Handles.Label(pathPoint.position, count.ToString());
            }
        }
    }
}

可以将此代码片段复制到您的Unity脚本文件中。确保脚本附加到场景中的对象上或打开Unity编辑器窗口。然后,将此脚本文件拖到场景中的任何对象上即可在编辑器模式下为对象显示编号。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-6-27 14:32 , Processed in 0.090787 second(s), 26 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表