Question by
noahl731 · Apr 06, 2019 at 02:28 PM ·
c#raycastraycasthit
Use raycast to change color
I have a cube that I want to change the color of when the raycast hits it, and when the raycast stops hitting the cube changes back to its original color. Here's what I have now
bool mouseOver;
Ray ray;
RaycastHit hit;
GameObject currentHit;
void Update()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Color startColor = Color.white;
if(Physics.Raycast(ray,out hit))
{
currentHit = hit.collider.gameObject;
if (currentHit.GetComponent<Collider>().tag.Equals("Item"))
{
mouseOver = true;
currentHit.GetComponent<Renderer>().material.color = Color.yellow;
} else {
mouseOver = false;
}
}
if(!mouseOver) {
if(currentHit.tag.Equals("Item")) {
currentHit.GetComponent<Renderer>().material.color = startColor;
currentHit = null;
}
}
}
This works when the raycast hits the cube but when the raycast stops hitting the cube, the color doesnt change. What am I doing wrong?
Comment
Answer by Hellium · Apr 06, 2019 at 05:09 PM
Following code not tested because I'm on my mobile phone.
public Color HighlightColor = Color.yellow ;
private Collider hitObject;
private Color initialColor;
private Material hitObjectMaterial;
private Camera camera;
private void Start()
{
camera = Camera.main;
}
private void Update()
{
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if( Physics.Raycast(ray,out hit) && hit.collider.CompareTag("Item") )
{
if( hitObject != null )
hitObjectMaterial.color = initialColor;
hitObject = hit.collider;
hitObjectMaterial = hitObject.GetComponent<Renderer>().material;
hitObjectMaterial.color = HighlightColor;
}
else if ( hitObject != null )
{
hitObjectMaterial.color = initialColor;
hitObject = null;
hitObjectMaterial = null;
}
}
Your answer
Follow this Question
Related Questions
Physics Raycast not working 1 Answer
raycasthit to set new move location 0 Answers
About AI detecting a sound 1 Answer
Player in front of enemy check not working, Physics.Raycast()? 1 Answer