Last active
October 2, 2016 17:37
-
-
Save pointcache/01f7057299577045aa9a68dbb4fa336d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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