I wrote this little bit of code to try to simulate OnMouseOver/Exit using Raycast using layers to ignore objects. When I hover the mouse over the object it turns green, but when I remove the mouse it’s supposed to turn white, but it’s not working. How can I get Raycast to act like OnMouseExit?
void Update () {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Transform other = null;
if (Physics.Raycast (ray, out hit, Mathf.Infinity, tileLayer)) {
if (other != hit.transform && other != null){
other.renderer.material.color = Color.white;
}
hit.transform.renderer.material.color = Color.green;
other = hit.transform;
}
else if (other != null){
other.renderer.material.color = Color.white;
}
}
Aha found the problem, had to put my other instantiation outside the Update function and it works perfectly. Here’s the code for anyone who has issues with objects in the way of your OnMouse functions and wants to use this. C#
using UnityEngine;
using System.Collections;
public class colorChange : MonoBehaviour {
public LayerMask tileLayer;
Transform other = null;
Color otherColor = Color.white;
void Update () {
// tile selection by mouse
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, Mathf.Infinity, tileLayer)) {
if (other == null){
otherColor = hit.transform.renderer.material.color;
}
if (other != hit.transform && other != null){
other.renderer.material.color = otherColor;
}
if (other != hit.transform){
otherColor = hit.transform.renderer.material.color;
}
hit.transform.renderer.material.color = Color.green;
other = hit.transform;
}
else if (other != null){
other.renderer.material.color = otherColor;
}
}
}
Edited for multiple colors to work properly.