Troubles with Raycast.

Hi people, I have problems with detecting a click over an object. I found an script and I translated it to C# (the syntax for the raycast gave me some problems, but it’s solved now), but it launchs onRollOver and onPress methods regardless of the mouse position. By the way, elementName is extended from the class GameElement (if someone asks where’s declared). I don’t know what I’m doing wrong, even If someone has another solution for mouse events on a game object it would be awesome.

Sorry If there are spelling mistakes, english isn’t my main lang :stuck_out_tongue:

Here’s the code.
Greetings :smile:

public class InteractiveElement : GameElement {

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		mouseActions();
	}
	
	void mouseActions()
	{	
		Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
      	RaycastHit hit;
      	
      	if(!Physics.Raycast(ray, out hit))
      	{
        	return;
      	}
		
		if (!hit.rigidbody || hit.rigidbody.isKinematic)
		{
			return; 
		}
		
		
		onRollOver(); 
		
		if (!Input.GetMouseButtonDown (0)) 
		return; 
		
		onPress(); 
	}
	
	void onRollOver()
	{
		Debug.Log("Rollover " + elementName);
	}
	
	void onPress()
	{
		Debug.Log("Press " + elementName);
	}
	
}

Use OnMouseOver, OnMouseEnter, OnMouseExit, etc. (It’s still doing raycasting behind the scenes, but saves you having to write it all out.)

–Eric

Ummh I tried this but nothing happens :/.

void OnMouseDown()
{
	Debug.Log("click");	
}
	
void OnMouseOver()
{
	Debug.Log("over");	
}

Does the object have a collider? It won’t work without one.

–Eric

Yep, it has a collider. I’ve been testing it and only works in some angles (and needs to be soooo close to the camera).

Maybe some other object is blocking it then. If so, put the blocking object on the IgnoreRaycast layer.

–Eric

Oh, I found the problem. My player’s game object has a big SphereCollider (trigger) around him to know what NPCs are close to him, I removed it at runtime and the mouse events worked fine. But I need to have this trigger :confused: Is there some way to tell the “raycast” to ignore this trigger?

Oh nice, didn’t see your post…
Let me try it :slight_smile:

Yep, it works perfect :smile:.
I know that was a very basic question, sorry for that.

Thanks mate :slight_smile: