Beispiel #1
0
    private static IEnumerator CoActivate(GameObject gameObject, ObjectCacheScript script)
    {
        yield return(waitForEndOfFrame);

        if (script != null)
        {
            if (!script.cached)
            {
                gameObject.SetActive(true);
            }
        }
    }
Beispiel #2
0
    public static CacheReference Instantiate(GameObject prefab, Vector3 position, Quaternion rotation, Transform parent = null)
    {
        Init();

        LinkedList <GameObject> objGroup = null;
        GameObject newObj = null;

        var prefabId = prefab.GetInstanceID();

        if (cache.TryGetValue(prefabId, out objGroup))
        {
            var node = objGroup.First;

            while (node != null)
            {
                var obj = node.Value;

                if (obj == null)
                {
                    Debug.LogError("ObjectCache: cached GameObject '" + prefab.name + "' was destroyed by an external script.");
                    node = node.Next;
                    objGroup.Remove(node.Previous);
                }
                else if (obj.GetComponent <ObjectCacheScript>().cached)
                {
                    var t = obj.transform;
                    t.position = position;
                    t.rotation = rotation;

                    t.localScale = prefab.transform.localScale;

                    t.parent = parent;

                    newObj = obj;
                    break;
                }
                else
                {
                    node = node.Next;
                }
            }
        }

        if (objGroup == null)
        {
            objGroup        = new LinkedList <GameObject>();
            cache[prefabId] = objGroup;
        }

        ObjectCacheScript script = null;

        if (newObj == null)
        {
            newObj = Object.Instantiate(prefab, position, rotation, cacheParent);

            newObj.SetActive(false);

            newObj.transform.parent = parent;

            // FIX: this line creates unnecessay garbage
            //newObj.name = prefab.name;

            if (maxInstancesPerPrefab == 0 || objGroup.Count < maxInstancesPerPrefab)
            {
                script = newObj.AddComponent <ObjectCacheScript>();
                objGroup.AddLast(newObj);
            }
        }
        else
        {
            script = newObj.GetComponent <ObjectCacheScript>();
        }

        if (script != null)
        {
            script.cached = false;
            //script.instanceId = instanceIdCounter++;
        }

        var cacheReference = new CacheReference(newObj);

        cacheScript.StartCoroutine(CoActivate(newObj, script));

        return(cacheReference);
    }