Check If Mouse Is Over An GameObject With Certain Tag Then Store That GameObject To Variable

Any help would be much appreciated as this is a core mechanic of my game.
Thanks

You’ll need to:

  1. Attach a collider component to your target game object. You can mark it as a trigger if you wish it to be passable.

  2. Attach the script I list here to the game object on which you wish to perform the mouse action. It can be any object…(just make sure you don’t destroy it).

  3. Tag the target game object with the tag you wish to test and change the “targetTag” variable in the editor! (not in the script since once you attach it, the change of public variables can only be done at the editor level).

    #pragma strict

    public var targetTag : String = “TagOfTarget”;

    private var currentGO : GameObject;
    private var v3out : Vector3 = Vector3.zero;

    function Update ()
    {
    if ( Input.GetMouseButtonDown(0) )
    {
    v3out.x = Input.mousePosition.x;
    v3out.y = Screen.height - Input.mousePosition.y;
    TestHit();
    }
    }

    private function TestHit()
    {
    var ray : Ray = Camera.main.ScreenPointToRay(v3out);
    var hitInfo : RaycastHit;

     if ( Physics.Raycast(ray, hitInfo) )
     {
     	if ( hitInfo.collider.CompareTag(targetTag) )
     	{
     		currentGO = hitInfo.collider.gameObject;
     	}
     }
    

    }