Ray casting onto a button

Hello, I am using this script to move my camera to multiple specified destinations by a click.

void Update () {
		if (Input.GetMouseButtonDown(0)) 
            clickCounter += 2;
			clicked = true;
			clickCounter = Mathf.Clamp(clickCounter, 0, camPositionList.Count-0); //ensures that number of clicks do not exceed the number of transforms in you list else you might get an Out of Range error
	     if (clicked)
			transform.position = Vector3.Lerp(transform.position, camPositionList[clickCounter].position, Time.deltaTime);
			if (transform.position == camPositionList[clickCounter].position) clicked = false;

I need to have this script move the camera when I click a button, or a certain part of the screen. I have been advised to use ray casting to achieve this, however I cannot figure out how to use ray casting to do so.

If anyone could show me how to use ray casting, or advise me of a better way to achieve this it would be extremely appreciated

If you’re using the UI system for button, I don’t think that raycasting is a good idea. You can create events for clicking a button. I have not been doing that so I can’t explain the process but maybe you’ll find some pointers here:


As for raycasting, it makes sense if you’d want to click, say - a point on the ground to let the camera move there. That would require a collider for the ground and if your scene is complex and you don’t want the walls or other objects to react to your raycast, you’ll also need a layermask. Defining a public LayerMask will easily let you set this in the inspector.

Here are some links that might help you get started with raycasting:

Also, this tutorial could really help you, you could use this script, with some adjustments - on your camera instead of the game object in the example to achieve the desired effect, I believe!

Have a great day! :slight_smile: