AddComponent returns wrong InstanceID

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!

Just to make sure, there is not PoolableObject component inside m_Prefab ?

1 Like

There isn’t supposed to be but in this one case someone added a PoolableObject component into the prefab!!! Didn’t spot that. Thanks for pointing it out - I’ll recode to do the GetComponent check first and add it if it’s not there.

Thanks again!

1 Like