1

I want to be able to tap a switch and have it slide to the other side. Right now that switch is a prefab with my code attached. When I add copies of that prefab all of them move not the individual one I clicked.

    // Start is called before the first frame update
void Start()
{
    
}

// Update is called once per frame
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit, 100.0f))
        {
            PrintName(hit.transform.gameObject);
        }
    }
}

private void PrintName(GameObject go)
{
    print(go.name);
    transform.position += new Vector3(3, 0, 0);
}

}

Chris
  • 59
  • 1
  • 3
  • Does this answer your question? [How to detect click/touch events on UI and GameObjects](https://stackoverflow.com/questions/41391708/how-to-detect-click-touch-events-on-ui-and-gameobjects) – Ruzihm Dec 11 '21 at 22:52
  • 2
    You're not checking if the click is happening on a particular object, your `if` is satisfied if **any** object is clicked. You could take the `Raycast` out of the `if` and check `hit.transform == transform` but the link above has cleaner options than writing a physics raycast – Ruzihm Dec 11 '21 at 22:53

1 Answers1

0

update function runs for all of your prefabs. basically, when you hit something with your raycast to something, every prefab that the script attached run PrintName function. thats why all of the prefabs move simultaneously.

ps: maybe you should go.transform.position instead of transform.position

mertcan
  • 45
  • 5
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 11 '21 at 23:56