Add script to prefab at runtime and OnMouseDown

I am creating a gameObject at runtime at a specific position on the screen as follow.

GameObject BoxGO = new GameObject(“BoxPrefab”);
GameObject Box = (GameObject)Instantiate (Box);
Box.transform.position = new Vector3 (pos_x, pos_y, pos_z);
Box.transform.parent = BoxGO.transform; = “Box_” + “” + z + “” + x;

I create 5 boxes at different locations on the screen. Next I want to click on any box and be able to change the color of the box.

In SelectedBoxScript I have:

private void OnMouseDown()
Debug.Log (;

But nothing happens. Any suggestions?

Easiest way is to just put the script on your prefab so it’s already on there.

You really want to use code button for code though as anything bigger than what you’ve posted would be really hard to read.

If you have to add the script when instantiating then do this: