You can set the camera's Y position once by setting it in one of the built-in functions that's executed only once. In Unity there's two such functions and they're called Start and Awake.
Some information about the two functions:
- The
Start function gets called on the frame when a script is enabled, just before any Update function is called the first time. - The
Start function is called only once during the lifetime of the script instance. - The
Awake function gets called when a script instance is being loaded. - Just like the
Start function, the Awake function is also only called once during the lifetime of the script instance. - The
Awake function is always called before any Start functions.
Based on the above information, we can make sure that the other object, let's call it the target object, is fully initialized and correctly positioned before the position information is retrieved from it and the camera's position is set.
I'm not very familiar with Unity so the code example below is pseudo code and needs to be adapted/edited to work in Unity.
// Script attached to the camera object public class CameraPositionScript : MonoBehaviour { // The target object which the camera object should retrieve the position from private GameObject target; void Awake() { // The target object has been initialised at this point, so it's safe to reference it here target = GameObject.FindWithTag("TargetName"); } void Start() { // Set the camera's Y position to the target object's Y position, this is done only once gameObject.transform.position.y = target.transform.position.y; } }