What's the best way to click on objects in game

I’ve looked up some videos involving this, and they said to use rays. But for some reason the object isn’t detecting the click. I’m not sure if I’m supposed to put the script into the object or some other object. Or even if I’m supposed use rays.

public class Swap : MonoBehaviour {

    public GameObject swappedInto;

    public Transform blankspace;
    void update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        //print("hello 1");
        if (Physics.Raycast(ray, out hit) && Input.GetMouseButtonDown(1))
        {

            if (hit.transform.position == transform.position)
            {
                print("hello");
                Instantiate(swappedInto, transform.position, transform.rotation);
                Destroy(gameObject);
            }
        }


    }
   

}

This script is supposed to swap one object into another object when it’s clicked on.

For Raycast to work there has to be an enabled collider on the things you wanna hit.

Your GetMouseButtonDown(1) also checks the middle button. Button zero is the primary left click:

In fact in most programming contexts, zero is almost always the first item, but not always.

Also, checking two Vector3 quantities for equality is not generally a good practice (line 14), since they can be vanishingly different and appear the same, and they test not equal in that case.

I think in this use case you are actually checking it for identifying itself, so that might be better accomplished with a tag or perhaps just comparing the transforms directly.

1 Like

@Kurt-Dekker Beat me to it, I would use an if statement tag check as well and I also don’t see any need for the && operator, you can just put the input inside the raycast and it will work fine.

I think he might need it, otherwise just moving the mouse over an object will zap it, right? I guess for a mobile touchscreen it would work…

OP, probably best if you wrap ALL of this code in a check of the mouse button, removing the mouse button check from where Lethn pointed out the && block.

This way, all this raycasting and whatnot isn’t happening every frame, only on the frame you click on.

Ahhh okay, that’s an optimisation thing to consider then isn’t it? Will keep that in mind.

How would I check for tags?

How would I put the input inside the raycast

simply make a separate if statement for the input mousekeydown and put the if statement for the raycast inside that, as for using tags check the documentation.

To use the tags you put them inside the raycast if statement.

Update, with a capital U. Yours is lowercase.

1 Like