Clicking on Objects with raycst, Getting Gameobject with raycst

Hey gang trying to select a target with recast, Tag, however it doesn’t seem to “Click” on my game object,
Did I miss a step here?

trying to set “Target” Gameobject, to the Gamobject the player clicks on with tag “Target”
is a basic box with Is-trigger that I am trying to click on.

(everything is tagged correctly yes the game object has a Collider, this script is on my Playercharatcer yes my camera is Tagged as MainCamera.)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TargetIngSystem : MonoBehaviour {


	Ray ray;
	RaycastHit hit;
	public int number = 0;
	public GameObject Target;

	void Start () {
		// Initialise ray
		ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		// Print out the current number value to the console window
		Debug.Log("Number is currently: " + number); 
	}

	void Update () {
		if (Input.GetMouseButtonDown (0)) {
			Debug.Log ("MouseDown");
			// Reset ray with new mouse position
			ray = Camera.main.ScreenPointToRay (Input.mousePosition); 
			if (Physics.Raycast (ray, out hit)) {
				if (hit.collider.gameObject.tag == "Target") {
					Target = hit.collider.gameObject;
					Debug.Log ("Hit");
				}

			}

		}	
	}




}

RayCast() will only return the first hit, if you have multiple colliders on your object it’s possible it’s always hitting the incorrect one. I’d suggest using RaycastAll() instead.

 void Update () {
     if (Input.GetMouseButtonDown (0)) {
         Debug.Log ("MouseDown");
         // Reset ray with new mouse position
         ray = Camera.main.ScreenPointToRay (Input.mousePosition); 
         RaycastHit[] hits = Physics.RaycastAll (ray);
         foreach (RaycastHit hit in hits) {
             if (hit.collider.gameObject.tag == "Target") {
                 Target = hit.collider.gameObject;
                 Debug.Log ("Hit");
             }
         }
     }    
 }

I’m not sure if you can do it but… why dont you use the built-in unity method for that. After all the OnMouseDown method does exactly that. The only difference is that it wont be done from the player script but from the object you want to be able to be clicked. Here you have two options, either you manually add a script with this to all your Targets or you create a scripts that puts this script on your targets using their tag.

Another posibility is that your hit.collider.gameobject is doing things weird, isn’t hit a gameobject already?