- Home /
Object Selection with large number of objects
I've got a scene with 10,000 GameObjects in it and I'm trying to implement Mouse Click object selection.
I've done this by doing the following:
- Attach a MonoBehaviour Component to the GameObject and override OnMouseDown().
- Add a Box Collider to the object to get mouse events.
I'm looking for a more optimal way to do this, something similar to this:
- When the user clicks the mouse, run a RayCast from the cursor location to see if it hits a GameObject. If it does, select that object.
Ideally, this logic only runs when the user clicks the mouse and I don't have to run OnMouseDown() on every one of my 10,000 GameObjects in every frame to determine a hit.
So the question I have is, which GameObject do I attach this script to so I only execute this logic when the user clicks the mouse? Or are there better ways to implement object selection?
Answer by · Sep 27, 2010 at 02:32 PM
You only need one instance of the script, and you can put it wherever you want. Probably on an empty GameObject, and name it SelectionManager or SelectionSystem (etc).
Here's a raycast selection snippet I've modified to your needs (updated to Javascript).
function Update ()
{
if ( Input.GetMouseButtonDown(0) )
{
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit, 100.0))
{
Debug.Log(hit.collider.gameObject.name);
}
}
}