Raycast not working ?

Hello there !

I’m having a problem with Raycasting. I’m using NGUI and I’m trying to implement some universal OnMouse(Enter/Exit/…)-like callback, but no matter what I try, I can’t get it working. Here’s the full code :

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Collider))]
public class cpTip : MonoBehaviour {

	// Use this for initialization
	void Start () 
	{
		
	}
	
	// Update is called once per frame
	void Update () 
	{
		//Debug.Log("Update()");
		Camera cam;
		Color color;
		if ( gameObject.GetComponent<UIWidget>() != null)
		{
			cam = UICamera.currentCamera;
			color = Color.red;
			Debug.Log(gameObject.name + " : UI Camera");
		}
		else
		{
			cam = Camera.mainCamera;
			color = Color.blue;
			Debug.Log(gameObject.name + " : Main Camera");
		}
		Ray ray = cam.ScreenPointToRay(Input.mousePosition);
		RaycastHit hit;
		if ( Physics.Raycast(ray, out hit, 100, gameObject.layer ) )
		{
			Debug.Log("Mouse over object");
		}
		Debug.DrawLine( ray.origin, ray.origin+ray.direction*10, color, 0, true);
	}
	
	void OnMouseOver()
	{
		//Debug.Log("OnMouseOver()");
	}
}

Can someone tell me what I’m doing wrong here ?

Thanks in advance :slight_smile:

Layer and LayerMask are not the same thing. You need to use the layer to set the correct bit in the mask…something like:

 if ( Physics.Raycast(ray, out hit, 100, 1 << gameObject.layer ) )