- Home /
 
How to change the color of a UI cross hair using Raycasts
Hello, I need help with a certain problem I am having with Unity 5. I have created a raycasting script in C# that simply allows me to destroy a certain object under the tag, "Objects".
I have also imported a custom UI cursor that I want the color changing of, through bool animations, when a certain object is being hovered over.
 using UnityEngine;
 using System.Collections;
 
 public class CursorChange : MonoBehaviour {
 
     public float distanceToSee;
     RaycastHit hit;  
     Animator anim;
 
     // Use this for initialization
     void Start () {
         anim = GetComponent<Animator> ();
         Cursor.visible = (false);
         anim.SetBool ("hasHit", false); 
     }
     
     // Update is called once per frame
     void Update () 
     {
         if(Physics.Raycast(this.transform.position, this.transform.forward, out hit, distanceToSee))
         {
             if(hit.collider.tag == "Objects")
             {
                 anim.SetBool ("hasHit", true);
             }
         }
     }
 }
 
               There are no compiler errors from this script yet the desired results are still not showing. Can anybody help?
Answer by Baste · Jun 08, 2015 at 08:10 AM
Where's this script attached?
Even if you have this on your camera, there's not really a 1-1 relation between directly forward from your camera and where the screen is.
To find out what you're looking at, use Camera.ScreenPointToRay - it creates a ray from the camera to the screen coordinates you input.
So, if you're using a free mouse, you want something like:
 Ray ray = Camera.ScreenPointToRay(Input.MousePosition);
 if(Physics.Raycast(ray, out hit, ...)
 
               If you're using mouse look, you'll want to use the center of the screen instead:
 Ray ray = Camera.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
 if(Physics.Raycast(ray, out hit, ...)
 
               Good luck!
Your answer
 
             Follow this Question
Related Questions
How to start Animation left turn With the cursor 1 Answer
Question about an inventory system idea 2 Answers
Animation and Position 2 Answers
Animation script 1 Answer
How to check if Animator is playing 3 Answers