obsidian/笔记文件/2.笔记/FileUtil.GetProjectRelativePath.md
2025-03-26 00:02:56 +08:00

31 lines
1.6 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#unity/日常积累
`FileUtil.GetProjectRelativePath` 是一个在Unity编辑器扩展或插件开发中常用的函数它用于获取指定文件相对于当前Unity项目的相对路径。这个函数非常有用因为它允许开发者在编写编辑器脚本时处理文件路径而不需要担心项目的具体存储位置。
要使用`FileUtil.GetProjectRelativePath`你需要将文件或目录的绝对路径作为参数传递给该函数。它将返回一个字符串表示该文件或目录相对于Unity项目根目录的路径。
以下是一个使用`FileUtil.GetProjectRelativePath`的示例:
``` cs
using UnityEngine;
using UnityEditor;
using System.IO;
public class ExampleScript
{
[MenuItem("Example/Get Relative Path")]
private static void GetRelativePath()
{
// 假设你有一个文件的绝对路径
string absolutePath = "/Users/yourusername/Projects/YourUnityProject/Assets/ExampleFolder/ExampleFile.txt";
// 使用FileUtil.GetProjectRelativePath获取相对于Unity项目的路径
string relativePath = FileUtil.GetProjectRelativePath(absolutePath);
// 输出相对路径
Debug.Log(relativePath); // 将输出Assets/ExampleFolder/ExampleFile.txt
}
}
```
在这个示例中,我们创建了一个名为`ExampleScript`的类,并在其中定义了一个静态方法`GetRelativePath`。这个方法通过`[MenuItem]`属性与Unity编辑器的一个菜单项相关联。当用户选择这个菜单项时它将获取一个硬编码的绝对路径并使用`FileUtil.GetProjectRelativePath`将其转换为相对于Unity项目的路径然后输出到控制台。