- Home /
Detecting OnMouseDown from colliders in an array
I am making a game where you have to select regions. Every region has its own collider that you click to select it. I have around 50 regions, and I don't want to make a script for every single one to tell when it has been clicked. Is there a way to make an array or a list in one script and then have it test each collider for all the other regions by itself?
Answer by dre38w · Nov 28, 2014 at 06:55 AM
You don't really need an array for this. Just place this on your camera.
void Update ()
{
Vector3 mousePos = Input.mousePosition;
Ray ray = Camera.main.ScreenPointToRay(mousePos);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo) && Input.GetMouseButtonDown(0))
{
curRegion = hitInfo.transform.gameObject;
}
}
This will fire a raycast through screen space wherever your cursor is located. Then whichever you click will set the curRegion variable to that clicked object. You may also want to check to make sure you are clicking only regions by setting a tag for all regions and then add this in your if statement:
if (hitInfo.transform.tag == "Regions")
This is doing nothing for me right now. Perhaps it is because my scene is 2D? $$anonymous$$y camera is set to perspective.
$$anonymous$$aybe I should Debug the ray. I tried doing this, but I couldn't format it right in my script.
This probably doesn't make a difference, but my colliders are polygon colliders. I tried setting them to "is trigger" and back, but it made no difference.
If this doesn't end up working we can go back to making an array.