[MenuItem("Tools/根据预设生成物品")]
public static void CreateDocTemplate()
{
GameObject templatePrefab = AssetDatabase.LoadAssetAtPath("Assets/Resources/Prefabs/DocTemplate/ResPrefab/Template_doc.prefab", typeof(GameObject)) as GameObject;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Assets/Resources/StaticXML/docTemp.xml");
XmlNodeList nodeList = xmlDoc.SelectNodes("//docTemp");
int index = 0;
foreach (XmlElement xe in nodeList)
{
index++;
string imageUrlStr = xe.GetAttribute("docUrl");
bool canInput = int.Parse(xe.GetAttribute("canInput")) == 1;
int inputFieldCount = int.Parse(xe.GetAttribute("inputFieldCount"));
if (!canInput || inputFieldCount > 0)
{
CreatTemplate(index, imageUrlStr, inputFieldCount);
}
}
AssetDatabase.SaveAssets();
}
private static void CreatTemplate(int index , string imageUrlStr , int inputFieldCount)
{
string savePath = templatePrefabPath + "/doc_" + index + ".prefab";
if (!File.Exists(savePath))
{
GameObject templateObj = PrefabUtility.InstantiatePrefab(templatePrefab) as GameObject;
string[] urlArr = imageUrlStr.Split(',');
Transform iamgeRoot = templateObj.transform.Find("Scroll View/Viewport/Content");
for (int i = 0; i < urlArr.Length; i++)
{
GameObject docImageGo = new GameObject("Sprite_doc");
docImageGo.transform.SetParent(iamgeRoot);
Image image = docImageGo.AddComponent<Image>();
Sprite sp = (Sprite)AssetDatabase.LoadAssetAtPath("Assets/_Atlas/DocTemplate/" + urlArr[i] + ".jpg", typeof(UnityEngine.Sprite));
if (sp == null)
{
Debug.LogError("图片不存在:" + "Assets/_Atlas/DocTemplate/" + urlArr[i] + ".jpg");
GameObject.DestroyImmediate(templateObj);
return;
}
image.sprite = sp;
image.GetComponent<RectTransform>().sizeDelta = new Vector2(sp.texture.width, sp.texture.height);
}
PrefabUtility.SaveAsPrefabAsset(templateObj, savePath);
GameObject.DestroyImmediate(templateObj);
Debug.Log("成功生成文书模板:doc_" + index);
}
}