[SOLVED] Raycast - Identifying target object

I can’t seem to figure this out. I must be doing something wrong.

I’ve got several buttons on the screen. I only want button1 to do something, all the other buttons should return miss, but when I run this code I get miss returns even when clicking on button1.

        if (Input.GetMouseButtonDown(0)) {      
            Ray toMouse = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo;
            bool didHit = Physics.Raycast(toMouse, out hitInfo);
            if (didHit) {
                if (hitInfo.collider.name == button1.ToString())
                {
                    Debug.Log("button1");
                }
                else
                {
                    Debug.Log("Miss");
                }
               


            } else {
                Debug.Log("nothing");
            }
        }

Can you try using CompareTag instead of name, let us check if the problem is about button1.ToString() or not. Just create a new tag called “Tag1”, add your tag to your button ( assuming your button has a collider ), and do this :

if(hitInfo.collider.CompareTag("Tag1")

Tag works, but it won’t work for my solution. You can’t move them around to different objects.

I’ve got 9 buttons which random colours get assigned to, and I want the player to be able to click the flashing button when it comes up.

I ‘could’ add 9 tags for the buttons, and work around the code - but that solution is less than ideal.

I just want to figure out why collider.name isn’t registering as a string.

EDIT:

Just solved it.

Changing the code to this seems to clear up the issue.

Thanks for putting me on the right track.

if (hitInfo.collider.name == button1.name)