Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

[SOLVED] Raycast - Identifying target object

Discussion in 'Scripting' started by Richard_Roth, Oct 11, 2015.

  1. Richard_Roth

    Richard_Roth

    Joined:
    Dec 29, 2014
    Posts:
    61
    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.


    Code (Csharp):
    1.  
    2.  
    3.         if (Input.GetMouseButtonDown(0)) {      
    4.             Ray toMouse = Camera.main.ScreenPointToRay(Input.mousePosition);
    5.             RaycastHit hitInfo;
    6.             bool didHit = Physics.Raycast(toMouse, out hitInfo);
    7.             if (didHit) {
    8.                 if (hitInfo.collider.name == button1.ToString())
    9.                 {
    10.                     Debug.Log("button1");
    11.                 }
    12.                 else
    13.                 {
    14.                     Debug.Log("Miss");
    15.                 }
    16.                
    17.  
    18.  
    19.             } else {
    20.                 Debug.Log("nothing");
    21.             }
    22.         }
    23.  
    24.  
     
  2. lineupthesky

    lineupthesky

    Joined:
    Jan 31, 2015
    Posts:
    92
    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 :

    Code (CSharp):
    1. if(hitInfo.collider.CompareTag("Tag1")
     
  3. Richard_Roth

    Richard_Roth

    Joined:
    Dec 29, 2014
    Posts:
    61
    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.

    Code (csharp):
    1.  
    2.  
    3. if (hitInfo.collider.name == button1.name)
    4.  
    5.  
     
    Last edited: Oct 11, 2015