- Home /
Variable to component keeps old value, even after using GetComponent<> again
My Problem:
I have a component in my script, and I set it using: GameObject.FindGameObjectByTag("MyTag").GetComponent<MyComponent>();
But in my game the gameObject I'm getting this component from gets destroyed, and re-instantiated regularly.
And when I set the components in my script again with GameObject.FindGameObjectByTag("MyTag")GetComponent<MyComponent>();
they still use the old reference, I checked this using: Debug.Log(componentVar.gameObject.name);
<- because the instantiated gameObject has a different name than the old one.
I have already tried to set the componentVar to null before setting it again, but it still used the old reference.
In short:
I need a way to confirm my componentVar is using the new reference instead of the old one.
Answer by henkehedstrom · Jan 07 at 10:42 AM
Do you have to use FindGameObjectsWithTag? Why are you destroying the object and creating it again?
I am not sure how the destruction and the instantiating happens but if there is another script that is handling that, that script could change componentvar.
You could have a function like: SetComponentVar(MyComponent myComponent){componentVar = myComponent;} in the script with the componentvar. Then when you instantiate a new object you also call this function and set the new component. If you use this solution you should not need the findgameobjectswithtag function either that could be slow but probably isn't in this case.
Your answer
