天天看點

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);
        }
    }
           
下一篇: jwt入門