Raycasting Mouse Clicks on specific objects

Hello,

I am currently trying to make a puzzle game that requires the use to make a selection between different choices on the screen. Currently, a red, blue, and green cube are the choices. I have figured out the code needed to do this. I add my code to one of the cubes and for now, when I click, it makes that object go away. When I attach this code to another cube, when I click, it makes both objects disappear. Here is my code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Cube2MouseMove : MonoBehaviour
{

Vector3 moveToPosition; // This is where the camera will move after the start
Vector3 backToPosition; // This is where the camera will move if not in the original position
float speed = 2f; // this is the speed at which the camera moves
bool cameraMoved = false; // this checks to see if the camera was moved

// Start is called before the first frame update
void Start()
{
    //Move the camera to this position
    moveToPosition = new Vector3(100, 0, -10);

    //Move the camera back to the starting position
    backToPosition = new Vector3(0, 0, -10);
}

// Update is called once per frame
void Update()
{
    //Mouse Click on Cube 2
    if (Input.GetMouseButtonDown(0))
    {

        //Create variables to cast a ray on Cube 2
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        //Detect if ray hit Cube 2
        if (Physics.Raycast(ray, out hit, 10f))
        {

        //If camera was not moved...
        if (!cameraMoved)
        {
        // Move the camera into position
        transform.position = Vector3.Lerp(transform.position, moveToPosition, speed);
        cameraMoved = true;
        }

        //If camera was moved...
        //else
        //{
        // Move the camera back into the starting position
        //transform.position = Vector3.Lerp(transform.position, backToPosition, speed);
        //cameraMoved = false;
        //}
    }
    }
}

}

So my question is, how do I make this code work so that if I click on any cube, it will disappear?

I want the code to make a cube to disappear only if it is clicked on, NOT if I click anywhere on the screen.

Thank you!

Hello, try to use hit.transform.gameObject in condition if (Physics.Raycast(ray, out hit, 10f)).


Hope it help.