- Home /
Question by
emmapy · Feb 13, 2020 at 02:35 PM ·
2dinstantiatefor-looponmousedown
OnMouseDown not firing on prefab instantiated in for loop (2D)
I want to instantiate a prefab ("swatches") on top of a child of a palette object. The swatch prefab has a "moveable" script attached to it which should output a message when the onMouseDown function fires. The instantiated objects always appear but the onMouseDown inside the moveable script fails when the size of the for loop is 3 or more (Despite there always being more palette children than swatches).
I can see the script is enabled but onMouseDown ONLY works when the for loop is of size 1 or 2
Does anyone know why this might be??
this is my for loop (which references the public game object swatchPrefab and the public int total swatches):
GameObject palette = GameObject.FindWithTag("palette");
for (int i = 0; i<totalSwatches; i++){
GameObject swatch = Instantiate(swatchPrefab);
swatch.transform.position = palette.transform.GetChild(i).transform.position;
if (swatch.GetComponent<moveable>() != null) Debug.Log("script exists"); //this is always true even when there is not click response
}
and this is my onMouseDown function inside the moveable script:
void OnMouseDown(){
Debug.Log("mousedown"); //does not fire when totalSwatches>2
GameObject active = GameObject.FindWithTag("activeSwatch");
if (active == this.gameObject || active == null) invert();
else {
swap(active);
}
}
Comment