59 lines
1.9 KiB
C#
59 lines
1.9 KiB
C#
using UnityEngine;
|
||
using System.IO;
|
||
using System;
|
||
|
||
public static class PathUtils
|
||
{
|
||
// 核心方法:获取相对路径(自动处理路径格式)
|
||
public static string GetRelativeToStreamingAssets(string targetPath, bool allowOutside = false)
|
||
{
|
||
string streamingAssetsPath = Application.streamingAssetsPath;
|
||
#if UNITY_EDITOR
|
||
streamingAssetsPath = "E:\\HQB\\文件打包\\0402\\10002\\App_Data\\StreamingAssets";
|
||
#endif
|
||
// 规范化路径格式(统一斜杠和大小写)
|
||
string normalizedBase = NormalizePath(streamingAssetsPath);
|
||
string normalizedTarget = NormalizePath(targetPath);
|
||
|
||
// 检查是否在StreamingAssets目录下
|
||
bool isInside = normalizedTarget.StartsWith(normalizedBase, StringComparison.OrdinalIgnoreCase);
|
||
|
||
if (isInside)
|
||
{
|
||
// 直接截取子路径
|
||
return normalizedTarget.Substring(normalizedBase.Length + 1);
|
||
}
|
||
else if (allowOutside)
|
||
{
|
||
// 使用Uri计算可能包含上级目录的相对路径
|
||
return GetRelativePathUsingUri(normalizedBase, normalizedTarget);
|
||
}
|
||
else
|
||
{
|
||
Debug.LogError($"路径不在StreamingAssets下: {targetPath}");
|
||
return null;
|
||
}
|
||
}
|
||
|
||
// 路径规范化工具
|
||
private static string NormalizePath(string path)
|
||
{
|
||
return Path.GetFullPath(path)
|
||
.Replace('\\', '/')
|
||
.TrimEnd('/')
|
||
.ToLower(); // 根据平台需求调整大小写敏感
|
||
}
|
||
|
||
// 使用Uri计算相对路径(支持跨目录)
|
||
private static string GetRelativePathUsingUri(string basePath, string targetPath)
|
||
{
|
||
var baseUri = new Uri(basePath + "/");
|
||
var targetUri = new Uri(targetPath);
|
||
|
||
Uri relativeUri = baseUri.MakeRelativeUri(targetUri);
|
||
string relativePath = Uri.UnescapeDataString(relativeUri.ToString())
|
||
.Replace('/', Path.DirectorySeparatorChar);
|
||
|
||
return relativePath;
|
||
}
|
||
} |