Same Object has different instances with different instanceIds

I have a Bar component that spawns a BarPrefab containing Bar. The Bar “constructor” sets some fields and returns the spawned component. But this spawned instance seems to be different then what is actually in-game - the testName is ignored and the instanceIds are different.


The instance ID of an object acts like a handle to the in-memory instance. It is always unique, and never has the value 0. Objects loaded from file will be assigned a positive Instance ID. Newly created objects will have a negative Instance ID, and retain that negative value even if the object is later saved to file. Therefore the sign of the InstanceID value is not a safe indicator for whether or not the object is persistent.


Maybe im fighting against Unity and doing some weird pattern but this seems like basic behavior. If Foo does not have the correct reference then how is it ever supposed to mutate any state on any other components? thank you for any insights!


class Foo: MonoBehavior {
  private void Start()
        {
            bar = Bar.Spawn(gameObject);

            //////////
            bar.testName;  // "testing"
            bar.GetInstanceID);  // 123
        }
}

class Bar: MonoBehavior {
  private string testName;

  public static Bar Spawn(GameObject parent)
    {
        // load prefab
        var go = Resources.Load("BarPrefab");
        Instantiate(go, parent.transform);

        // get the BAR component from the prefab
        var bar = go.GetComponent<Bar>();

        //////////
        // Update ignores this 
        bar.testName = "testing";

        return bar;
    }

  private Update() {
    testName;  // NULL ???
    GetInstanceID()  // -1232 ???
  }
}

This is the only thing in the scene so its not like theres some hidden objects somewhere. Inspecting Foo, it has the correct hierarchy and seems to be the same object with the correct hierarchy, but its clearly not.


Also worth noting that i’ve used similar patterns before years ago (im on 2022.2 now)

Hi, you are calling Instantiate() without assigning the result to go, so you create an instance, but you modify and return the loaded Prefab object instead, so in Bar’s Update() method (of the unmodified instance in this case) you see different stuff than in Foo’s Start(). Try

go = Instantiate(go, parent.transform);