erfan erfan - 2 months ago 32
C# Question

move camera with button in unity

i want move Main Camera with button . its my game play :
enter image description here

its my scene:

enter image description here

want when click in button , main camera move to right in another pic .
this is my script for button :

public void Uss(GameObject camera) {

Vector3 temp = transform.position;
temp.x += 0.1f;
camera.transform.position = temp;

}

Answer

In your script, the button is moved, not the camera. You should move the GameObject of the main camera instead.

Transform cameraTransform; 
void Start()
{
    cameraTransform = Camera.main.gameObject.transform;
}
public void Update()
{
    cameraTransform.Translate(7, 0, 0);
}

But I recommend you write the logic in the onClick handler of the button like below.

Attach a script to the button GameObject

float step = 100;//find a proper value for this
void Start()
{
    Button b = gameObject.GetComponent<Button>();
    b.onClick.AddListener(
        ()=>
        {
            Camera.main.gameObject.transform.Translate(step, 0, 0);
        }
    );
}

The step value is dependent on the size of your pictures.

I haven't tested the script but it should work in that way.

Comments