2d OnMouseDown failure

Hi
I’m working on a game which takes place on a 6x6 grid and the player clicks on a square to make a move.

So far I have the grid showing nicely, and as far as I am aware, I have all the code in place to make the game print some text to the console when the player clicks on a square.

This is where I’ve gotten stuck, clicking does nothing.

I have 2 scripts, MasterController.cs which is my gamecontroller and creates the grid programmatically and attaches a BoxCollider2d and my own GridSquare code.
My second script is GridSquare.cs which captures the grid clicks and passes them to MasterController.cs.

The OnMouseDown function in GridSquare.cs has a debug call to test the function works. This fails with the squares on my 6x6 grid.

I’m certain the code in GridSquare.cs must be correct, as I’ve dropped a square into the scene in the Unity editor and attached a GridSquare and BocCollector2D component and it works.

This DID suggest that maybe the BoxCollider2D or GridSquare components I add in MasterController.cs either didn’t get added, or maybe got removed somehow.

To test this, I’ve put some code in the MasterController.cs update function to grab the 1st square and check it has BoxCollider2D and GridSquare added, looks good when I test it so I’m still stumped.

As far as I can see, I’ve done everything correct, but there must be something I am missing.

Can any helpful feeling people see where I am going wrong please? :slight_smile:

MasterController.cs

using UnityEngine;
using System.Collections;

public class MasterController : MonoBehaviour {

    public GameObject lightBlueSquareObject;
    public Sprite lightBlueSquareSprite = new Sprite();
    public GameObject darkBlueSquareObject;
    public Sprite darkBlueSquareSprite = new Sprite();

    private GameObject testCounter;

    private float screenHeightHalf = 0.0f;
    private float screenWidthHalf= 0.0f;
    private float screenHeight = 0.0f;
    private float screenWidth= 0.0f;

    private float tileHeightHalf = 0.0f;
    private float tileWidthHalf= 0.0f;
    private float tileHeight = 0.0f;
    private float tileWidth= 0.0f;

    private Vector3[,] board = new Vector3[6,6];

    public void InitScreen(){
        screenHeightHalf = Camera.main.orthographicSize;
        screenWidthHalf = Camera.main.aspect * Camera.main.orthographicSize;
        screenHeight = screenHeightHalf * 2;
        screenWidth = screenWidthHalf * 2;
    }

    public void InitGraphics(){
        lightBlueSquareObject = GameObject.FindGameObjectWithTag("lightBlueSquare");
        lightBlueSquareSprite = new Sprite();
        lightBlueSquareSprite = lightBlueSquareObject.GetComponent<SpriteRenderer>().sprite;
        Destroy(lightBlueSquareObject);
       
        darkBlueSquareObject = GameObject.FindGameObjectWithTag("darkBlueSquare");
        darkBlueSquareSprite = new Sprite();
        darkBlueSquareSprite = darkBlueSquareObject.GetComponent<SpriteRenderer>().sprite;
        Destroy(darkBlueSquareObject);

        tileHeight = lightBlueSquareSprite.bounds.size.y;
        tileWidth = darkBlueSquareSprite.bounds.size.x;
        tileHeightHalf = tileHeight / 2;
        tileWidthHalf = tileWidth / 2;
    }

    public void InitBoard(){
        for(int yCnt = 0; yCnt <= 5; yCnt++){
            for(int xCnt = 0; xCnt <= 5; xCnt++){
                var tempX = (xCnt*tileWidth)-(tileWidth*3);
                var tempY = (yCnt*tileHeight)-(tileWidth*3);
                board[xCnt,yCnt] = new Vector3(tempX,tempY,1);
                testCounter = new GameObject();
                testCounter.tag = "square";
                testCounter.AddComponent<SpriteRenderer>();
                testCounter.AddComponent<BoxCollider2D>();
                testCounter.AddComponent<GridSquare>();
                testCounter.GetComponent<GridSquare>().Init(xCnt,yCnt);
                if((xCnt + yCnt)%2==0){
                    testCounter.GetComponent<SpriteRenderer>().sprite = lightBlueSquareSprite;
                }
                else{
                    testCounter.GetComponent<SpriteRenderer>().sprite = darkBlueSquareSprite;
                }
                ////Debug.Log(testCounter.GetComponent(SpriteRenderer).sprite.bounds.size.x);
                testCounter.transform.position = board[xCnt,yCnt];
            }
        }
    }

    public void ProcessBoardClick(GameObject clickedSquare){
        Debug.Log(clickedSquare.GetComponent<GridSquare>().GetX() + ":" +  clickedSquare.GetComponent<GridSquare>().GetY());
    }

    // Use this for initialization
    void Start () {
        InitScreen();
        InitGraphics();
        InitBoard();   
    }
   
    // Update is called once per frame
    void Update () {
        if (Input.GetMouseButton(0)){
            GameObject testSquare = GameObject.FindGameObjectWithTag("square");
            if(testSquare.GetComponent<BoxCollider2D>() != null){
                Debug.Log("Box Colider is added");
            }
            if(testSquare.GetComponent<GridSquare>() != null){
                Debug.Log("GridSquare is added");
            }
        }
    }
}

GridSquare.cs

using UnityEngine;
using System.Collections;

public class GridSquare : MonoBehaviour {

    private int x = 0;
    private int y = 0;

    // Use this for initialization
    void Start () {
   
    }
   
    // Update is called once per frame
    void Update () {
        if (Input.GetMouseButton(0)){
            Debug.Log("updating square");
        }
    }

    public int GetX(){
        return x;
    }

    public int GetY(){
        return y;
    }

    public void Init(int newX, int newY){
        x = newX;
        y = newY;
        Debug.Log("Init grid square");
    }

    public void OnMouseDown(){
        Debug.Log ("Mouse click");
        GameObject.FindGameObjectWithTag("GameController").GetComponent<MasterController>().ProcessBoardClick(gameObject);
    }

}

I’m not sure what your problem is, but looking at this section:

testCounter = new GameObject();
testCounter.tag = "square";
testCounter.AddComponent<SpriteRenderer>();
testCounter.AddComponent<BoxCollider2D>();
testCounter.AddComponent<GridSquare>();

You may want to consider creating the object separately and saving it as a prefab, that way you could just create it using Instantiate and wouldn’t have to attach components at runtime.

Thanks to anyone who looked over this.
I’ve managed to resolve it myself.

After a lot more googling and experimentation I believe the collider hasn’t been moved properly when I moved the square on line 69. It might even be too close to the camera which apparently causes problems.

To fix it I’ve moved the original line 59 -

testCounter.AddComponent<BoxCollider2D>();

To just below line 69 -

testCounter.transform.position = board[xCnt,yCnt];

Works great now.