Example #1
0
    void UpdateRenderables <T>(
        List <T> renderables,
        GameObject newObject,
        List <GameObject> objectPool,
        BidirectionalMap <T, GameObject> renderableObjectMap,
        Transform uiContainer,
        System.Action <GameObject> onCreateCallback = null)
        where T : IRenderable
    {
        // Put all GameObjects in a set, and remove the objects that are still in used
        HashSet <GameObject> unusedObjects = new HashSet <GameObject>(renderableObjectMap.Values);

        foreach (T renderable in renderables)
        {
            GameObject uiObject;
            // Spawn new UI person
            if (!renderableObjectMap.ContainsKey(renderable))
            {
                if (objectPool.Count > 0)
                {
                    uiObject = objectPool[objectPool.Count - 1];
                    objectPool.RemoveAt(objectPool.Count - 1);
                    uiObject.SetActive(true);
                }
                else
                {
                    uiObject = Instantiate(newObject);
                }
                uiObject.transform.SetParent(uiContainer, false);
                renderableObjectMap.Add(renderable, uiObject);
                if (onCreateCallback != null)
                {
                    onCreateCallback(uiObject);
                }
            }
            else
            {
                uiObject = renderableObjectMap.GetValue(renderable);
                unusedObjects.Remove(uiObject);
            }
            renderable.RenderTo(uiObject);
        }
        foreach (GameObject uiObject in unusedObjects)
        {
            renderableObjectMap.RemoveValue(uiObject);
            objectPool.Add(uiObject);
            uiObject.SetActive(false);
            uiObject.transform.SetParent(null, false);
        }
    }