Unity 代码修改场景上的prefab后保存
Talk is cheap, show me the code
多说无益,上代码
[MenuItem("[Tools]/场景/一键替换导航网格面")]
static void TransNav()
{
GameObject obj = GameObject.Find("NavMeshObj");
if(obj && obj.transform.childCount > 0)
{
Object prefab = PrefabUtility.GetPrefabParent(obj);
if(prefab)
{
string str = AssetDatabase.GetAssetPath(prefab);
string path = str.Replace(".prefab", ".obj");
GameObject tmp = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject)) as GameObject;
if(tmp)
{
GameObject instTmp = Instantiate(tmp, obj.transform);
Transform[] instChilds = instTmp.GetComponentsInChildren<Transform>();
for (int i = 0; i < instChilds.Length; i++)
{
MeshRenderer mr = instChilds[i].GetComponent<MeshRenderer>();
if (mr)
{
mr.enabled = false;
instChilds[i].gameObject.AddComponent<MeshCollider>();
instChilds[i].gameObject.layer = 10;
}
}
GameObject.DestroyImmediate(obj.transform.GetChild(0).gameObject);
PrefabUtility.ReplacePrefab(obj, prefab, ReplacePrefabOptions.ConnectToPrefab);
AssetDatabase.SaveAssets();
}
}
}
}