selecting blocks on mouse click

I have a 2.5d type game, with falling blocks (like tetris) and orthographic projection setup (I’ve setup my game as “3D” type).

I’ve defined a block like this:

public class Block{
	public Block () {
		this.gameObj = GameObject.CreatePrimitive (PrimitiveType.Cube);
	}
        public GameObject gameObj;
}

I have a BoardMgr (GameObj + script only component), where I spawn these blocks and store them in an array:

public class BoardMgr : MonoBehaviour {
	protected Block[] blocks;
	protected Block[,] board;
}

In BoardMgr::update(), blocks are falling down one after the other (like tetris). Now, I’d like to figure out when I click on a block, which block object is it. This is the click detection code:

if (Input.GetMouseButtonDown(0)) {
			Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
			RaycastHit hit;
			if (Physics.Raycast (ray, out hit)) {
				Debug.Log ("Ray hit block");
				// How do I find which block got hit here ?
			} else {
				Debug.Log ("Ray missed block");
			}
		}

When I click on a block, I do see the ray hit block on console, but then, how do I access which “Block” object got hit ? From RayCastHit, hit object, how do I decode which Block does it reference ?

I’m new to unity (2 days old) but not new to gamedev. Trying to find my way through unity here. I’d appreciate if someone can point me in the right direction here.

or simply put… try something like:

if (Input.GetMouseButtonDown(0)) {
             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
             RaycastHit hit;
             if (Physics.Raycast (ray, out hit)) {
                  Debug("Ray hit " + hit.collider);
             } else {
                 Debug.Log ("Ray missed block");
             }
         }

I ended up instantiating all the blocks at Awake() and store them in a dictionary indexed by getInstanceId(). When I select an object, I index into the dictionary like this hit.transform.gameObject.GetInstanceID (). Saves me from looping :slight_smile:

I have multiple clicks happening and lot of objects. If I end up looping for all of them checking for object, it would slow down! O(n) vs O(1)