While playing I am moving the camera (z) with a slider in the inspector. I want the slider to take into account the current camera z position but when I do that, the slider no longer moves the camera. Here is the code that does move the camera but the camera z position is set to 0.
using UnityEngine;
using System.Collections;
public class Main_FadeWithCameraDistance : MonoBehaviour
{
[Range(-100, 100)]
public float cameraZSlider;
public Vector3 cameraPos;
void Update()
{
CameraLocation();
}
void CameraLocation()
{
cameraPos.x = Camera.main.transform.position.x;
cameraPos.y = Camera.main.transform.position.y;
cameraPos.z = cameraZSlider;
Camera.main.transform.position = cameraPos;
}
}
If my camera is at -20 z, I want the slider to be at -20 and the camera at -20 when hit play and for the slider to still work. cameraZSlider = Camera.main.transform.position.z doesn’t work since I can no longer use the slider.
I would recommend to write everything in “FixedUpdate” function. It is updating constantly and there will be no lags.
And calling the “CameraLokation”-function every frame in the update methode is quiet unefficient, put it directly in the Update or FixedUpdate function.
Now to your question:
You want to control the Z-position of your camera with a slider in your inspector, right?
And the script is sitting on the camera you want to move?