Interactable objects - One component on each with OnMouseDown vs Raycasting

I am making an RTS, and have roughly 2000 trees on a map.
If I right click these trees, peasants should go to them.

My question is, should I have a component on each tree that checks OnMouseEnter/Exit and OnMouseDown, or should I have a singleton constantly raycasting my mouse position, and reacting differently depending on what object I am current hitting w my raycast?

Using individual components is a lot cleaner, but then I also need 2000 objects listening after a mouse interaction.

Using raycast will require quite a dirty if statement that I can see getting out of hand fast as I add more and more interactable objects, but might be more performant?

Constant raycasting would be expensive. Try using a single script to react to the right-click and identify the selected object. This would only require a momentary raycast (set the ray length as required).

Once you have the information you can transition your peasant characters as required. Adding a layermask would be useful for identifying specific object types.

Here’s a basic example script…

Example Script

using UnityEngine;

public class TargetIndentifier : MonoBehaviour {
   // Private Declarations
   private Camera cameraReference;
   private Ray targetRay;
   private RaycastHit targetHit;
   private int targetRayLength = 250;
   private bool inputDisabled;
 
   // --
   void Awake () {
       // Component References
       cameraReference = Camera.main;
   }
   // --
   void Update () {
       // Get User Input
       if (!inputDisabled && Input.GetMouseButtonDown(1)) {
           targetRay = cameraReference.ScreenPointToRay(Input.mousePosition);
           if (Physics.Raycast(targetRay, out targetHit, targetRayLength)) {
               MoveCharacters(targetHit.transform);
           }
       }
   }
   // --
   void MoveCharacters(Transform target) {
       // Debug Target Check
       print(target);
       // Set Input Flag
       inputDisabled = true;
       // Move Characters
       // >>>> Your Code Here <<<<
       // Reset Input Flag
       inputDisabled = false;
   }
}

Thanks man, that is a good idea.

For now I have chosen to go with one component on each with a MouseDown, will optimize it in the future if I need to :slight_smile: Then its great to have this as a source!

1 Like