Skip to content

Instantly share code, notes, and snippets.

@pointcache
Last active October 2, 2016 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pointcache/01f7057299577045aa9a68dbb4fa336d to your computer and use it in GitHub Desktop.
Save pointcache/01f7057299577045aa9a68dbb4fa336d to your computer and use it in GitHub Desktop.
using UnityEngine;
using System;
using System.Collections.Generic;
//Create and call getcomponent through it instead.
public class ComponentCache
{
private GameObject owner;
private Dictionary<Type, Component> cache = new Dictionary<Type, Component>();
public ComponentCache(GameObject go)
{
owner = go;
}
public T GetComponent<T>() where T : Component
{
Component val;
if (cache.TryGetValue(typeof(T), out val))
{
if (val != null)
{
return val as T;
}
else
{
var comp = owner.GetComponent<T>();
if (comp != null)
{
cache[typeof(T)] = comp;
return comp;
}
else
{
return null;
}
}
}
else
{
var comp = owner.GetComponent<T>();
if (comp != null)
{
cache.Add(typeof(T), comp);
return comp;
}
else
{
return null;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment