在多人协作项目中,我们都会将物体做成预设体 然后代码中进行加载,下面就介绍下预设体管理的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
using UnityEngine; using System.Collections; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; #endif //[ExecuteInEditMode] public class PrefabManager : MonoBehaviour { [SerializeField] GameObject[] mPrefabs = new GameObject[0]; // 用来存储预设体 [SerializeField] Transform mStatic; // 静态物体父对象 [SerializeField] Transform mUI; // UI物体父对象 [SerializeField] Transform mOther; // 其它物体父对象 [SerializeField] Transform mNetwork; // 网络相关物体父对象 void Start() { //yield break; for (int i = 0, end = mPrefabs.Length; i < end; ++i) { CreateObj(mPrefabs[i]); } } /// <summary> /// 创建预设物体 并按类型设置到对应父对象下面 /// </summary> /// <param name="go"></param> /// <returns></returns> private GameObject CreateObj(GameObject go) { GameObject result; #if UNITY_EDITOR if (!Application.isPlaying) { result = PrefabUtility.InstantiatePrefab(go) as GameObject; } else #endif { result = GameObject.Instantiate(go); } result.name = go.name; //是界面放到UIRoot下 if (result.isStatic) { result.transform.parent = mStatic; } else if (result.GetComponent<RectTransform>() != null) { result.transform.SetParent(mUI, false); } else { result.transform.parent = mOther; } return result; } #if UNITY_EDITOR Dictionary<int, GameObject> mThings = new Dictionary<int, GameObject>(); /// <summary> /// 可以在Inspector下 右键加载预设体 /// </summary> [ContextMenu("LoadPrefab")] private void LoadPrefab() { if (PrefabUtility.prefabInstanceUpdated == null) { // 这种方法只能监听到修改某个prefab的实例后点击Apply时,无法监听直接修改prefab的属性 PrefabUtility.prefabInstanceUpdated = delegate { AssetDatabase.SaveAssets(); }; } UnloadPrefab(); for (int i = 0, end = mPrefabs.Length; i < end; ++i) { mThings.Add(i, CreateObj(mPrefabs[i])); } } /// <summary> /// 可以在Inspector下 右键移除预设体 /// </summary> [ContextMenu("UnloadPrefab")] private void UnloadPrefab() { foreach (var pair in mThings) { GameObject go = PrefabUtility.GetPrefabParent(pair.Value) as GameObject; PrefabUtility.ReplacePrefab(pair.Value, go); } foreach (var pair in mThings) { GameObject.DestroyImmediate(pair.Value); } mThings.Clear(); } #endif } |
相对应 还要增加该管理预设体
- 本文固定链接: http://www.u3d8.com/?p=580
- 转载请注明: 网虫虫 在 u3d8.com 发表过