Hi guys,
I have a prefab (gets instantiated at run-time) which contains a script. In this script I declare a GameObject water (to reference an object already instantiated in my hierarchy) and in start() I do:
water = GameObject.Find("Water");
Another script constantly changes the water-object’s Y-position and indeed when I run I can see it changing. However, when I access the water-object’s Y-position from my prefab script it constantly gives me only the initial Y-position of water even though it’s actually changing. How do I do it so that I’m retrieving the current Y-value of water?
transform.position returns the current position so you are doing that correctly. It sounds like the object you are moving is not the same as the ‘Water’ object you are referencing in your scripts.
You can easily check if this is the case. Make the water reference a public variable in your script so that you can click on that object and see what it is via the inspector at runtime.
You’re not trying to cache a reference to the position vector are you?
That doesn’t work, it will create a copy and act exactly as you describe. Vectors can’t be referenced. You have to fetch it directly from the gameobject every time.
Also, don’t use GameObject.Find - @KelsoMRK pointed out one of the potential issues with it in this case. This seems like the time for a singleton, or perhaps FindWithTag.