Alright so right now I made it so function OnMouseDown() selects an enemy but I’m not sure how to make it so if you click into empty 3d space that it will deselect that object. Any idea how to do this ?
If you’re looking to click in space, just setup a large collider behind everything and cast a ray to detect clicking on that, if you detect clicking on that you can assume you have not hit something in front of it. You could avoid raycasting and stick with your OnMouseDown() for that if you wish. Remember you’ll need to store which object is currently selected in a central place and then swap that for null or nothing or whatever your deselected state is when clicking on the large background collider.
Try attaching the following script to the object you want to select. The object needs to have a collider for this to work (this is required by OnMouseDown anyway).
using UnityEngine;
using System.Collections;
public class SelectObject : MonoBehaviour
{
public bool objectSelected = false;
// Update is called once per frame
void Update ()
{
// Set as not hit
objectSelected = false;
// If the left mouse button was clicked
if(Input.GetMouseButtonUp(0))
{
// Do a raycast towards the object
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (collider.Raycast (ray, out hit, (Camera.main.gameObject.transform.position - transform.position).magnitude))
{
if(hit.collider.gameObject == this.gameObject)
// hit
objectSelected = true;
}
}
}
}