1. 在场景中实例化Prefab
public GameObject LoadPrefabToScene(string loadPath,string prefabName)
{
//加载路径
string loadFullPathName = string.Format("{0}/{1}.prefab",loadPath,prefabName);
//加载预制体
GameObject prefabSource = AssetDatabase.LoadAssetAtPath<GameObject>(loadFullPathName);
if(prefabSource == null)
{
Debug.LogError("加载路径错误 : " + loadFullPathName);
return null;
}
//在场景中实例化
GameObject prefabGameObj = PrefabUtility.InstantiatePrefab(prefabSource) as GameObject;
//修改物体信息
prefabGameObj.transform.position = Vector3.zero;
prefabGameObj.transform.rotation = Quaternion.identity;
prefabGameObj.transform.localScale = Vector3.one;
prefabGameObj.transform.SetAsLastSibling();
//解除预制体关系
if(PrefabUtility.IsAnyPrefabInstanceRoot(prefabGameObj))
PrefabUtility.UnpackPrefabInstance(prefabGameObj,PrefabUnpackMode.OutermostRoot,InteractionMode.AutomatedAction);
//
return prefabGameObj;
}
2. 修改Prefab实例,可以增删修改子节点,比如给制定名字的子节点添加组件
public void AddComponentByName<T>(GameObject root,string startSignStr) where T : Component
{
if(root == null || root.transform.childCount == 0)
return;
for(int i = 0; i < root.transform.childCount; i++)
{
GameObject child = root.transform.GetChild(i).gameObject;
string name = child.name;
if(name.StartsWith(startSignStr))
{
child.AddComponent<T>();
}
if(root.transform.childCount > 0)
AddComponentByName<T>(child,startSignStr);
}
}
3. 保存Prefab,删除场景中的实例
public bool SaveNewPrefab(GameObject prefabGameObj,string savePath,string prefabName)
{
if(prefabGameObj == null)
return false;
if(!Directory.Exists(savePath))
Directory.CreateDirectory(savePath);
string fullPath = string.Format("{0}/{1}.prefab",savePath,prefabName);
if(File.Exists(fullPath))
{
Debug.LogError("同名文件已存在 : " + fullPath);
return false;
}
bool savePrefabResult;
PrefabUtility.SaveAsPrefabAsset(prefabGameObj,fullPath,out savePrefabResult);
GameObject.DestroyImmediate(prefabGameObj);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
if(savePrefabResult)
Debug.Log("保存成功 : " + fullPath);
else
Debug.LogError("保存失败 : " + fullPath);
return savePrefabResult;
}
4. 可以省略prefabName参数,批量编辑文件夹下多个Prefab···
本文来自博客园,作者:萧然CS,转载请注明原文链接:https://www.cnblogs.com/z-c-s/p/15112855.html
浙公网安备 33010602011771号