1

So I have this code attached to a Quad.

public class ShapeGrid : MonoBehaviour {

public GameObject[] shapes;

void Start(){
    GameObject[,] shapeGrid = new GameObject[3,3];
    StartCoroutine(UpdateGrid());
}

IEnumerator UpdateGrid(){
    while (true) {
        SetGrid ();
        yield return new WaitForSeconds(2);
    }
}

void SetGrid(){
    int col = 3, row = 3;
    for (int y = 0; y < row; y++) {
        for (int x = 0; x < col; x++) {
            int shapeId = (int)Random.Range (0, 4.9999f);
            GameObject shape = Instantiate (shapes[shapeId]);
            shape.AddComponent<ShapeBehavior>();
            Vector3 pos = shapes [shapeId].transform.position;
            pos.x = (float)x*3;
            pos.y = (float)y*3;
            shapes [shapeId].transform.position = pos;
        }
    }
}

The script above generates Game Objects at run time, to which I assigned another script:

public class ShapeBehavior : MonoBehaviour {

    void OnMouseDown(){
        Debug.Log ("Destroy");
        Destroy (gameObject);
    }
}

The problem is, sometimes the OnMouseDown() executes, sometimes it does not. I cannot figure out why , and how to fix it.

Red Viper
  • 477
  • 1
  • 5
  • 22
jeanl
  • 379
  • 2
  • 7
  • 18

2 Answers2

2

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.

Exerion
  • 449
  • 7
  • 20
  • 1) I don't think it's with the position because sometimes it works on a specific location, sometimes not. 2) Again, not with the position. 3) No RigidBody on any objects. 4) Objects already have collider. 5) I'm only using 1 camera. 6) I still dont think it's the position? 7) Still nothing. :( Thank you though – jeanl Oct 20 '15 at 08:26
  • the most comprehensive answer on this problem I have seen. It solved my issue because I had 2 cameras. I dont know how to solve the issue with 2 cameras though...Thanks anyways. edit: I found to solve the issue with 2 cameras. Increase the priority of your main camera...that is it. – Aykut Karaca Jul 24 '20 at 18:36
0

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.

Paweł Marecki
  • 630
  • 1
  • 9
  • 21
  • The shapes in ShapeGrid class already have a collider. So if I add a collider on every cloned game object, I get this error: Can't add component 'BoxCollider' to circle(Clone) because it conflicts with the existing 'BoxCollider2D' derived component! – jeanl Oct 20 '15 at 06:59
  • You said "sometimes", can you check if problem exists on same object or is this totaly random thing? Also You can check layers, object cant be on Ignore Raycast layer. – Paweł Marecki Oct 20 '15 at 07:35
  • Been trying to find a pattern. I think it's random. And I don't think I'm using Raycasts either – jeanl Oct 20 '15 at 08:22
  • Mayby this is stupid question but... Are the scripts ShapeBehavior are enabled on all objects? Edit: One more thing, can you try to Instantiate objects with possition and rotation? I'm not sure but i think that i got some problem with rotation parameter some time ago. Mayby Quaternion.Identity for rotation. I'm not sure, just try to find out :) – Paweł Marecki Oct 20 '15 at 08:36
  • Wow thank you so so much!!! It worked. I changed it to this: shape.transform.position = new Vector3((float)x*3, (float)y*3, 0f); – jeanl Oct 20 '15 at 08:47
  • Ok, i'll edit changes in answer to clear the view for a problem :) I'm glad to help you. – Paweł Marecki Oct 20 '15 at 08:48