Some of end users calling multiple times TryGetComponent on my Target class.(Target class is attached to hundreds of targets)
IOT make they life easier was thinking about caching components which they requesting instread to using TryGetComponent on each frame,so:
added:
public class NonExistentMarker
{
private NonExistentMarker() { }
public static readonly NonExistentMarker Instance = new NonExistentMarker();
}
**then in my Target class, added:
**
readonly Dictionary<Type, object> m_cachedComponents = new Dictionary<Type, object>();
public bool HadCachedComponent<T>(out T component)
{
var componentType = typeof(T);
if (m_cachedComponents.TryGetValue(componentType, out var obj))
{
if (obj is NonExistentMarker)
{
component = default;
return false;
}
component = (T)obj;
return true;
}
if (TryGetComponent<T>(out component))
{
m_cachedComponents.TryAdd(componentType, component);
return true;
}
else
{
m_cachedComponents.TryAdd(componentType, NonExistentMarker.Instance);
return false;
}
}
code working as expected, and storing reference to requested by end-users components but it’s slight slower than normal GetComponent, any advice how to make it faster?
**OFC was using single component like this:
**
bool m_wasEnabled_CachedStealthComponent = false;
bool m_had_CachedStealthComponent = false;
Stealth m_stealth;
public bool Cached_StealthComponent(out Stealth _stealth)
{
if (!m_wasEnabled_CachedStealthComponent)
{
m_had_CachedStealthComponent = TryGetComponent<Stealth>(out m_stealth);
m_wasEnabled_CachedStealthComponent = true;
}
_stealth = m_stealth;
return m_had_CachedStealthComponent;
}
they are fast, and easy but required hardcoding all of components….
as written above had code solution but is not fast enough