- Home /
Only change a variable on the instaniated object not the prefab.
Hi everyone,
I am having a bit of trouble setting a variable on an instantiated object. What I want to achieve is to instantiate an object and set a variable after. Which works fine. However this object spawns a prefab based on him the only difference is that some variables have different values. However now when I change one variable when instantiating the prefab. It also changes on the other objects/prefabs. And that's not what I want I want to set the variable only on the object it instantiated in the first place not the prefab.
The code I use (which works but I only want it to work on the object not the prefab)
GameObject newOG = Instantiate(prefab, transform.position, Quaternion.Euler(-90,0,0)) as GameObject;
MyRoom r = newOG.gameObject.GetComponent<MyRoom>();
r.isOG = true;
How could I achieve this?
Greetings,
I think your code should work as you wanted because you're setting it on the instantiated object, not the prefab. Can you show the whole script and $$anonymous$$yRoom script? $$anonymous$$aybe there are other references that interfere?
There should be no problem with your code. $$anonymous$$aybe 'isOG' is a static variable??
$$anonymous$$aybe 'isOG' is a static variable??
That was my first thought, given that the var is changing on all instances. But it wouldn't compile, because they're accessing it through an instance (although to be fair, I think @Lilius's hunch that we're not seeing the real code, or at least not everything that's relevant, is a good one).
Probably not the cause, but this looks odd...
$$anonymous$$yRoom r = newOG.gameObject.GetComponent<$$anonymous$$yRoom>();
...when would normally do this...
$$anonymous$$yRoom r = newOG.GetComponent<$$anonymous$$yRoom>();
I'm not sure what I'd expect GameObject.gameObject
to return, is it possible that it's returning the prefab for some reason?
ohhh you're right. I didn't even notice the Gameobject.gameObject
thing. That has got to be the problem. Too bad I can't test it right now