Reputation: 13
So I'm trying to do this thing where if I left click on an object, 1 is added to a variable, and if I right click on it, 1 is subtracted from that variable. The left click works fine, but when I right click, nothing is happening.
public class cs_SliderClick : MonoBehaviour
{
public int sliderValue;
void Start ()
{
}
void Update ()
{
}
public void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
{
sliderValue += 1;
}
if (Input.GetMouseButtonDown(1))
{
sliderValue -= 1;
}
}
}
Can anyone tell me what I'm doing wrong here?
Thanks.
Upvotes: 0
Views: 2217
Reputation: 66
So I would recommend to call the OnMouseDown() Function inside of the Update Method.
public class cs_SliderClick : MonoBehaviour {
public int sliderValue;
void Start ()
{
}
void Update ()
{
OnMouseDown();
}
public void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
{
sliderValue += 1;
}
if (Input.GetMouseButtonDown(1))
{
sliderValue -= 1;
}
}
}
Upvotes: 0
Reputation: 125455
You need to use Unity's EventSystems
.
Implement IPointerClickHandler
and then override the OnPointerClick
function.
Attach PhysicsRaycaster
to the camera if the GameObject is a 3D Mesh. If this is a 2D game then attach Physics2DRaycaster
to the camera.
Below is your fixed code:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class cs_SliderClick : MonoBehaviour, IPointerClickHandler
{
public int sliderValue;
void Start()
{
//Attach PhysicsRaycaster to the Camera. Replace this with Physics2DRaycaster if the GameObject is a 2D Object/sprite
Camera.main.gameObject.AddComponent<PhysicsRaycaster>();
addEventSystem();
}
public void OnPointerClick(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Left)
{
Debug.Log("Left click");
sliderValue += 1;
}
else if (eventData.button == PointerEventData.InputButton.Right)
{
Debug.Log("Right click");
sliderValue -= 1;
}
}
//Add Event System to the Camera
void addEventSystem()
{
GameObject eventSystem = null;
GameObject tempObj = GameObject.Find("EventSystem");
if (tempObj == null)
{
eventSystem = new GameObject("EventSystem");
eventSystem.AddComponent<EventSystem>();
eventSystem.AddComponent<StandaloneInputModule>();
}
else
{
if ((tempObj.GetComponent<EventSystem>()) == null)
{
tempObj.AddComponent<EventSystem>();
}
if ((tempObj.GetComponent<StandaloneInputModule>()) == null)
{
tempObj.AddComponent<StandaloneInputModule>();
}
}
}
}
Upvotes: 3