无法让对象响应右键单击

时间:2016-07-06 21:21:21

标签: c# unity3d

所以我试图做这件事,如果我左键单击一个对象,1会被添加到变量中,如果我右键单击它,则从该变量中减去1。左键单击工作正常,但是当我右键单击时,没有任何事情发生。

 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;
         }
     }
 }

谁能告诉我我在这里做错了什么?

感谢。

2 个答案:

答案 0 :(得分:1)

您需要使用Unity的EventSystems

实施IPointerClickHandler,然后覆盖OnPointerClick功能。

如果GameObject是3D网格,请将PhysicsRaycaster附加到相机。如果这是2D游戏,则将Physics2DRaycaster附加到相机。

以下是您的固定代码:

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>();
            }
        }
    }

}

答案 1 :(得分:0)

所以我建议在Update方法中调用OnMouseDown()函数。

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;
         }
     }
 }