Want a way to touch on object to look at it then touch anywhere else to stop looking

When I touch on a gameobject called “enemy” or “enemy1” my player looks at them but when I touch on the UI joystick it stops looking at them. I need a way to look at the enemy until I tap anywhere else on the screen (excluding UI joystick) but also if I touch “enemy1” change the LookAt to that

Thanks

void Update()
    {
        if (movementEnabled == true)
        {
            Move();
        }

        if (lookAtEnemyEnabled == true)
        {
            LookAtTarget();
        }

        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = cam.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            //Hit specific layers
            if (Physics.Raycast(ray, out hit, 300, hittable))
            {
                Debug.Log(hit.transform.name);
            }

            //Hit specific game objects
            if (Physics.Raycast(ray, out hit, 300))
            {
                if (hit.collider.gameObject.name == "enemy")
                {
                    lookAtEnemyEnabled = true;
                    lookAtEnemyIndex = 0;
                }
                else if (hit.collider.gameObject.name == "enemy1")
                {
                    lookAtEnemyEnabled = true;
                    lookAtEnemyIndex = 1;
                }
            }
        }

        if (lookAtEnemyIndex == 0)
        {
            playerMustLookAt = GameObject.Find("enemy").transform;
        }

        if (lookAtEnemyIndex == 1)
        {
            playerMustLookAt = GameObject.Find("enemy1").transform;
        }
    }

Found a solution shortly after posting

I created a new private int called NOThittable, this selects all layers except the ones the enemies are on

then added an “else if” section into the raycast and it all seems to work fine :slight_smile:

Updated code below

if (Input.GetMouseButtonDown(0))
        {
            Ray ray = cam.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            //Hit specific game objects
            if (Physics.Raycast(ray, out hit, 300, hittable))
            {
                if (hit.collider.gameObject.name == "enemy")
                {
                    lookAtEnemyEnabled = true;
                    lookAtEnemyIndex = 0;
                }

                if (hit.collider.gameObject.name == "enemy1")
                {
                    lookAtEnemyEnabled = true;
                    lookAtEnemyIndex = 1;
                }
            }

            else if (Physics.Raycast(ray, out hit, 300, NOThittable))
            {
                lookAtEnemyEnabled = false;
                lookAtEnemyIndex = -1;
            }
        }