文件流方式 删除prefab空脚本

时间:2023-03-08 21:49:11
文件流方式 删除prefab空脚本
 /// <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 = ; 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);
}
}