看了这个问题,好几天,试验了雨松的方式还是不行,只好采用他最后建议的文件流的方式。再次贴一下核心代码。
/// <summary>
/// 删除一个Prefab上的空脚本
/// </summary>
/// <param name="path">prefab路径 例Assets/Resources/FriendInfo.prefab</param>
private void DeleteNullScript(string path)
{
bool isNull = false;
string s = File.ReadAllText(path);
Regex regBlock = new Regex("MonoBehaviour");
// 以"---"划分组件
string[] strArray = s.Split(new string[] { "---" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < strArray.Length; i++)
{
string blockStr = strArray[i];
if (regBlock.IsMatch(blockStr))
{
// 模块是 MonoBehavior
Match guidMatch = Regex.Match(blockStr, "m_Script: {fileID: (.*), guid: (?<GuidValue>.*?), type:");
if (guidMatch.Success)
{
// 获取 MonoBehavior的guid
string guid = guidMatch.Groups["GuidValue"].Value;
//Debug.Log("Guid:" + guid);
if (string.IsNullOrEmpty(GetScriptPath(guid)))
{
// 工程中无此脚本 空脚本!!!
//Debug.Log("空脚本");
isNull = true;
// 删除操作
// 删除MonoScript
s = s.Replace("---" + blockStr, "");
Match idMatch = Regex.Match(blockStr, "!u!(.*) &(?<idValue>.*?)\r");
if (idMatch.Success)
{
// 获取 MonoBehavior的guid
string id = idMatch.Groups["idValue"].Value;
// 删除MonoScript的引用
Regex quote = new Regex(" - (.*): {fileID: " + id + "}");
s = quote.Replace(s, "");
}
}
}
}
}
if (isNull)
{
// 有空脚本 写回prefab
File.WriteAllText(path, s);
// 打印Log
Debug.Log(path);
}
}
谢谢!