How to call a public Method from a script via UI button

I have a script attached to my Main camera, it controls everything that has to do with the controlling the camera. How do I have the public method “ResetCamera()” that is defined on the Main camera controller script with the UI button I have on the canvas.

In the Inspector for the button, find the “OnClick ()” section, press the + button to add a new click handler, then drag the camera onto the new row, then select “ResetCamera()” from the dropdown list that appears.

1 Like

I take it back, My button isn’t working.

public void ResetCamera()
    {
        Debug.Log("Button Pressed")
        this.gameObject.transform.position = new Vector3(0, 0, -100);
        this.gameObject.transform.rotation = new Quaternion(0, 0, 0, 1.0f);
    }

This is what the code does.
Everything else appears correct On Click(), Editor and Runtime, The Camera is definitely selected. and CameraController.ResetCamera() is the function!?!?!?

Edit: “Button Pressed” does not fire.

Did you add in a Debug.Log or Print so that it’s conclusive that the function isn’t actually running? It may be running and just not changing anything. If the camera is parented to another object, then a position and rotation change will put it back relative to the parent’s origin and not in a specific location in global coordinates. Be sure that “interactable” and “isOn” are both true in the Button script’s configuration in the inspector too.

Also, be sure you’re selecting the camera object in the scene and not the prefab, maybe? I don’t know, I’m a bit confused. I’ve also had a situation where I copied the button and the one I was “pressing” was not the one that I THOUGHT I was pressing…

Hmm, does the button actually change color and appear to be clicked when you click it? If not, there are a couple of reasons it might not be getting clicked. Make sure “Interactable” is checked in the Button inspector, and also it needs to be in a hierarchy somewhere under a “Canvas” that has a Graphic Raycaster. Unity should do all that automatically but if you moved it out of the hierarchy or something that could cause it to stop picking up mouse clicks.

It worked after I deleted the canvas, and added a new canvas, and new button. This time I was getting a bunch of build errors, input axis horizontal not defined. I went and reset the input, and it worked. Weird.