Search code examples
c#unity-game-enginenavmesh

How to follow the unit when you click the mouse


I need my unit to move to the enemy when i clicking mouse on enemy and destroy when my unit touch him

For moving i use navmesh and raycast hit

All units have navmesh agent

Enemies moving by points

picture for better understanding


Solution

  • Lot of ways to do that: i give you the global idea and you adapt to your script i have set layer for enemy to "enemy" just to be sure to chase a clicked enemy. layer enemy = 8 in my sample

    3 phases:

    First phase: Click detection and trap the gameobject clicked

    private bool chasing = false;
    public Transform selectedTarget;
    
        if (Input.GetMouseButtonDown(0))
        {
            //Shoot ray from mouse position
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit[] hits = Physics.RaycastAll(ray);
    
            foreach (RaycastHit hit in hits)
            { //Loop through all the hits
                if (hit.transform.gameObject.layer == 8)
                { //Make a new layer for targets
                    //You hit a target!
    
                    selectedTarget = hit.transform.root;
                    chasing = true;//its an enemy go to chase it
                    break; //Break out because we don't need to check anymore
                }
            }
        }
    

    Second phase: chase the enemy. so you have to use colliders and at least one rigidbody, you have plenty of tutorial which explains how to detect collision.

        if (chasing)
        {
            // here i have choosen a speed of 5f
            transform.position = Vector3.MoveTowards(transform.position, selectedTarget.position, 5f * Time.deltaTime);
        }
    

    Destroy on Collision with OnCollisionEnter (or InTriggerEnter)

    void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.tag == "enemy")
        {
            Destroy(col.gameObject);
        }
    }
    

    The given code is for 3d game, if you are using a 2d game, just adapt the code to 2D, no difficulties to do that .