u3d 工具写法:实现根据预设模板和配置,生成预设物体

	[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
            GameObject templateObj = PrefabUtility.InstantiatePrefab(templatePrefab) as GameObject;
            //以下为对新的 GameObjece 进行设置,根据不同需求设计
            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);
        }
    }