- Home /
transform.LookAt not updating each frame until UI Slider input is changed
I have an object that moves around my scene, and I want my camera to always be looking at it. I used transform.LookAt(target), and that was fine, but then I wanted to add a UI Slider so that the player can make the camera look above or below the target. I thought I could just update the Y value in my Vector3 target, but now the camera only updates to look at the target immediately after the slider value has been changed.
An additional symptom of the UI Slider being added is that when the scene loads, the camera now points directly at the world origin before the slider value is changed. I want it to be looking directly at the target on load, and at all times (plus or minus the slider value).
This is the script I have attached to my camera:
public Transform target;
private Vector3 targetPosition;
private float targetX;
private float targetZ;
private float targetY;
void Awake(){ //I added Awake to stop it looking at the world origin on load - didn't work.
transform.LookAt (target);
}
void Update () {
transform.LookAt (target); //Added it here as well, just in case. Also does nothing.
targetX = target.transform.position.x; //I tried putting these variables into Update() -
targetY = target.transform.position.y; //once again, does nothing.
targetZ = target.transform.position.z;
transform.LookAt (targetPosition);
}
public void cameraRotation(float yHeight){ //UI Slider value feeds into yHeight
targetPosition = new Vector3 (targetX, (yHeight + targetY), targetZ);
}
If I take everything out and just have transform.LookAt(target), it works as intended, without the added Y value.
Answer by Bunny83 · Sep 22, 2016 at 12:18 PM
Since "target" can change it's position at any time it makes no sense to use it's position in the slider callback which of course is only called when the slider is updated. Just do this:
public Transform target;
private float heightOffset;
void Update ()
{
Vector3 targetPos = target.position + Vector3.up * heightOffset;
transform.LookAt (targetPos);
}
public void cameraRotation(float yHeight)
{
heightOffset = targetY;
}