【问题标题】:how to get the number of click in unity c#如何在unity c#中获取点击次数
【发布时间】:2017-03-03 20:00:27
【问题描述】:

我目前正在编写一个统一的c#脚本,主要思想是当我点击模型的某个部分时,该部分将被突出显示,现在我希望再次点击它恢复到原始状态。当我第三次单击同一部分时,它应该再次突出显示。

我不知道如何在 Update() 方法中实现它,因为每次点击都要花费几帧,我无法识别第二次点击、第三次点击等是哪一帧。

有什么方法可以在不统一考虑帧数的情况下识别点击次数?

 void Update(){
    if (Input.GetMouseButton(0))
    {
        RaycastHit hit;

        if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit)){
                bone = hit.collider.transform;
                if (boneList.Contains(bone) != true)
                {
                    /* if the part is not chosen before, add it to the list and highlight all elements in the list */
                    boneList.Add(bone);
                    Highlight(boneList);
                }/*cannot delete the element chosen repetitively*/
    }
}}

【问题讨论】:

  • 听起来你想要Input.GetMouseButtonDown()(或Input.GetMouseButtonUp())而不是Input.GetMouseButton()
  • @squill25 没关系,程序员的回答看起来比我目前可以投入的时间要全面得多。只要问题得到解决。 =P

标签: c# unity3d unity5


【解决方案1】:

你离得很近。 else 语句应该添加到您的代码中。你的逻辑应该是这样的:

if(List contains clickedObject){
    Remove clickedObject from List
    UnHighlight the clickedObject
}else{
    Add clickedObject to List
    Highlight the clickedObject
}

此外,就像提到的Serlite,您必须使用GetMouseButtonDown 而不是GetMouseButton,因为按下键时会调用一次GetMouseButtonDown,但按下键时每帧都会调用GetMouseButton

最终的代码应该是这样的:

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        RaycastHit hit;

        if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
        {
            bone = hit.collider.transform;


            if (boneList.Contains(bone))
            {
                //Object Clicked is already in List. Remove it from the List then UnHighlight it
                boneList.Remove(bone);
                UnHighlight(boneList);
            }
            else
            {
                //Object Clicked is not in List. Add it to the List then Highlight it
                boneList.Add(bone);
                Highlight(boneList);
            }
        }
    }
}

您必须编写UnHighlight 函数,该函数基本上将传入的 GameObject/Transform 恢复为其默认状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多