Skip to content

Instantly share code, notes, and snippets.

@mqp
Last active September 23, 2016 00:57
Show Gist options
  • Save mqp/ff8ce81f792cfe536c20188361d1487c to your computer and use it in GitHub Desktop.
Save mqp/ff8ce81f792cfe536c20188361d1487c to your computer and use it in GitHub Desktop.
ComponentCachedGameObject example
using System;
using System.Collections.Generic;
using UnityEngine;
public static class ComponentCachingDemo
{
public static Dictionary<int, ComponentCachedGameObject> gameObjectsByMeshId;
public static void AddObjects()
{
gameObjectsByMeshId[0] = new ComponentCachedGameObject(GameObject.Find("Mesh0"));
gameObjectsByMeshId[1] = new ComponentCachedGameObject(GameObject.Find("Mesh1"));
}
public static void DoStuff()
{
gameObjectsByMeshId[0].GetComponent<ThreeJSMeshController>().enabled = false;
}
}
/// <summary>
/// A reference to a GameObject that maintains a cache of the object's components.
/// </summary>
public class ComponentCachedGameObject
{
public readonly GameObject GameObject;
/// <summary>
/// All of the currently cached components for this object, indexed by their component type.
/// </summary>
private readonly IDictionary<Type, Array> Cache;
public ComponentCachedGameObject(GameObject gameObject)
{
GameObject = gameObject;
Cache = new Dictionary<Type, Array>();
}
public T GetComponent<T>() where T : Component
{
var components = GetComponents<T>();
return components.Length > 0 ? components[0] : null;
}
public T[] GetComponents<T>() where T : Component
{
var key = typeof(T);
Array components;
if (!Cache.TryGetValue(key, out components))
{
components = Cache[key] = GameObject.GetComponents<T>();
}
return (T[])components;
}
public void Invalidate()
{
Cache.Clear();
}
public void Invalidate<T>()
{
Cache.Remove(typeof(T));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment