如何检测鼠标是否在对象Unity C#上

时间:2020-09-14 18:56:59

标签: c# unity3d

我一直在用Unity 3D开发游戏,其中涉及能够拾取一些物体。我当前的代码如下:

using System.Collections;

using System.Collections.Generic; 使用UnityEngine;

public class pickUp : MonoBehaviour
{
  public Transform dest;
  void OnMouseDown() {
      GetComponent<Rigidbody>().useGravity = false;
      GetComponent<Rigidbody>().velocity = new Vector3(0f, 0f, 0f);
      GetComponent<Rigidbody>().angularVelocity = new Vector3(0f, 0f, 0f);
      this.transform.position = dest.position;
      this.transform.parent = GameObject.Find("Destination").transform;
    }

  void OnMouseUp() {
    this.transform.parent = null;
    GetComponent<Rigidbody>().useGravity = true;
  }
  void Update() {
//where I need to detect mouseover    
  }
}

正如注释中所隐含的那样,我需要检测鼠标是否位于对象上方,否则,它将关闭所有其他对象的物理功能。我也无法对名称进行编程(因此使用Ray),因为已经有许多对象使用了该脚本。

谢谢!

编辑:旧版本的代码,放入当前版本

2 个答案:

答案 0 :(得分:0)

我认为您缺少了一些东西,void OnMouseDown(),OnMouseOver(),OnMouseUp(),仅调用了附加了对撞器和脚本的特定对象,无论您使用相同的对象多少次都没有关系多个对象的脚本。这些方法与每个对象无关。

答案 1 :(得分:0)

您原来的问题代码看起来像这样

void Update() 
{
    if (Input.GetMouseButton(0)) 
    {
        void OnMouseOver() 
        {
            //where I need to detect mouseover 
        }
    }
}

几乎已经存在,但是将其声明为Update内的嵌套方法当然没有任何意义!

您的脚本应该看起来像

public class pickUp : MonoBehaviour
{
    public Transform dest;

    // You should already set this via the Inspector
    [SerializeField] private Rigidbody _rigidbody;

    private void Awake()
    {
        // or as fallback get it ONCE
        if(!_rigidbody) _rigidbody = GetComponent<Rigidbody>();
    }

    private void OnMouseDown() 
    {
        _rigidbody.useGravity = false;
        _rigidbody.velocity = Vector3.zero;
        _rigidbody.angularVelocity = Vector3.zero;

        transform.position = dest.position;
        transform.parent = GameObject.Find("Destination").transform;
    }

    private void OnMouseUp() 
    {
        transform.parent = null;
        _rigidbody.useGravity = true;
    }

    // Called every frame while the mouse stays over this object
    private void OnMouseOver() 
    {
        if (Input.GetMouseButton(0)) 
        {
            // whatever shall happen every frame while mouse over and mouse button 0 stays pressed
        }
    }
}

或者,如果仅在鼠标进入并存在该对象时才需要做某事,而不要使用

private void OnMouseEnter()
{

}

private void OnMouseExit()
{

}
相关问题