Sometimes OnMouseDown() method in Unity executes, sometimes it does not

后端 未结 2 1357
半阙折子戏
半阙折子戏 2021-01-07 08:40

So I have this code attached to a Quad.

public class ShapeGrid : MonoBehaviour {

public GameObject[] shapes;

void Start(){
    GameObject[,] shapeGrid = ne         


        
相关标签:
2条回答
  • 2021-01-07 09:05

    Probably you have to add colliders to all of objects because OnMouse events are based on collisions. Here is detailed info: Unity Docs - OnMouseDown

    Edit: after some talks we find out that the problem was caused by Instantiate method.

    It's allways a better way to fill all of parameters in Instantiate method e.g

    Instantiate(prefab, Vector3.zero, Quaternion.Identity)

    if you want, you could change any of these parameters after instantiating object.

    0 讨论(0)
  • 2021-01-07 09:17

    There are plenty of possible reasons.

    1. Collider conflict. OnMouseDown() is raycasting under the hood. If the ray from the mouse position strikes another collider (visible or not), you don't get the OnMouseDown() call.
    2. Distance from the camera. The OnMouseDown implementation uses a depth limit for raycasting which may cause the object to not register the clicks.
    3. RigidBody. OnMouseDown works completely differently if there is a RigidBody somewhere in the hierarchy. It actually won't call OnMouse functions on the clicked object but it will instead call them on the RigidBody's game object instead (yet another bug).
    4. Collider missing. OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider, so you have to add collider to your object.
    5. Multiple cameras. Due raycasting, having several cameras may cause a problem.
    6. Collider is colliding with another collider on the mouse position.
    7. Just wild bug. Closing and reopening Unity Editor as the last hope.

    If nothing of this doesn't help you should implement IPointerDownHandler interface and use it instead of OnMouseDown.

    0 讨论(0)
提交回复
热议问题