Esempio n. 1
0
        /// <summary>
        /// Load a game object prefab at the specified path. This is equivalent to Resources.Load, but it will
        /// also consider DataNode-exported binary assets as well, automatically loading them as if they were
        /// regular prefabs.
        /// </summary>

        static public GameObject LoadPrefab(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return(null);
            }
            if (!Application.isPlaying)
            {
                return(Resources.Load(path, typeof(GameObject)) as GameObject);
            }

            GameObject prefab = null;

            if (mPrefabRoot == null)
            {
                GameObject go = new GameObject("Prefabs");
                Object.DontDestroyOnLoad(go);
                mPrefabRoot = go.transform;
                mPrefabs.Clear();
            }

            // Try to get it from cache
            if (mPrefabs.TryGetValue(path, out prefab))
            {
                return(prefab);
            }

            if (prefab == null)
            {
                // Load it from resources as a Game Object
                prefab = Resources.Load(path, typeof(GameObject)) as GameObject;

                if (prefab == null)
                {
                    // Load it from resources as a binary asset
                    byte[] bytes = UnityTools.LoadBinary(path);

                    if (bytes != null)
                    {
                        // Parse the DataNode hierarchy
                        DataNode data = DataNode.Read(bytes);

                        if (data != null)
                        {
                            // Instantiate and immediately disable the object
                            prefab = data.Instantiate();

                            if (prefab != null)
                            {
                                mPrefabs.Add(path, prefab);
                                Object.DontDestroyOnLoad(prefab);
                                prefab.transform.parent = mPrefabRoot;
                                prefab.SetActive(false);
                                return(prefab);
                            }
                        }
                    }
                }
            }

            if (prefab == null)
            {
#if UNITY_EDITOR
                Debug.LogError("[TNet] Attempting to create a game object that can't be found in the Resources folder: [" + path + "]");
#endif
                prefab = GetDummyObject();
            }

            mPrefabs.Add(path, prefab);
            return(prefab);
        }