Hello
I have a project which generates 100 gameObjects scattered about, and I want to add a script which detects which gameObject my mouse clicked on.
My uncertainty is where would i attach a C# script for this?
Should i attatch the script to all 100 gameObjects and check if the mouse clicked that one specific gameObject or create a script which gets the relevant gameObject via some kind of loop, if the latter where should i attach such a script to ? An empty gameObject or the camera? Or can i have scripts that do “checks” without it being assigned to a gameObject in the world?
it is of course advisable to have code which does the same for multiple gameobjects, in one place, but for 100 objects on the computer, I don’t think it’s too bad, I wouldn’t do it though.
depending on these two conditions a solution can be different:
- do the gameobjects have colliders
- does the camera move
If they have colliders use raycast and the camera’s screenpointtoray. If they don’t, transform their positions into the camera space. compare x and y with the mouse position and z if you find multiple. It’s an approximation though. If the camera does not move, you can cache those positions.
an empty gameobject in the scene is fine