Just spent a pleasant hour trying to track down a bug and it came down to this bit of code.
var go = Instantiate(m_Prefab,parent.transform);
var ps = go.AddComponent(typeof(PoolableObject));
ps.TTL = 2;
return go;
Looked OK to me but the TTL was always wrong - it was always the default value of ten.
Turns out that the reference which AddComponent returns is not the one in the gameobject!!
If you do AddComponent followed by GetComponent the you get the correct reference.
var go = Instantiate(m_Prefab,parent.transform);
var ps = go.AddComponent(typeof(PoolableObject));
var newps = go.GetComponent<PoolableObject>();
if ( newps != ps )
Debug.Log($"{newps.GetInstanceID()} {ps.GetInstanceID()}" );
newps.TTL = m_TTL;
return go;
You’ll see the InstanceIDs are not the same and the reference returned by GetComponent<> works as expected, but the one from AddComponent<> does not.
No idea why!