EventType.MouseUp && Event.button

Greetings,

Simple question, I am using this code and it give me this errors even though its an 100% copy from the documentation;

void OnMouseUp() {
	Event e = Event.current;
	
	if (e.button == 0 && e.isMouse){
            Debug.Log("Left Click");
	}else{
            Debug.Log("NOT-Left Click");
		
	}
}

Object reference not set to an instance of an object!

Someone know why this happens to me?

Thanks!

Hi,

I think you have to implement it in the OnGUI() function. For each event OnGUI is called in the scripts (Unity - Scripting API: Event), otherwise the Event.current is null.

Additional, if you wanna check a mouse click, you can differ between mouse down and mouse up like this.

void OnGUI()
{
	if (Event.current.button == 0)
	{
		if (Event.current.type == EventType.MouseDown)
		{				
			//...
		}
	}
}

I hope this helps you.

Greets

Hi,

    // Left Click
	void OnMouseUp()
	{
		Debug.Log("OnMouseUp Left Click");
	}
	
	// Right Click
	void OnGUI()
	{
		if (Event.current.button == 1)
	    {
	       if (Event.current.type == EventType.MouseDown)
	       {          
	       		Camera currentCamera = Camera.main;		// take the current camera SceneView or gameView doesn't matter
				if(currentCamera == null)
					return;
				
				Vector3 mouseposition = Input.mousePosition;
				Ray screenRay = currentCamera.ScreenPointToRay( mouseposition );
				
				RaycastHit rayhit;
		        if(!Physics.Raycast(screenRay, out rayhit))
				{
					return;
				}
				
				if(rayhit.collider == collider)
					Debug.Log("OnMouseUp Left Click");
	       }
	    }
	}

This works for me, but the implementation in OnGUI needs a collider, don’t forget

public static bool LeftMouseUp()
{
return Event.current != null && Event.current.type == EventType.MouseUp && Event.current.button == 0;
}