Boolean being overwritten

So I have a method that checks to see if you clicked on an ‘enemy’ gameobject. I want to be able to deselect the enemy by clicking away, say on some terrain, and I tried doing this with booleans.

       if (Input.GetMouseButtonDown(1))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            
            foreach (string enemy in enemyTitles)
            {
                if (Physics.Raycast(ray, out hit) && target != null)
                {
                    target.transform.position = hit.point;

                    //Check to see if you right-clicked on an enemy from the array.
                    if (hit.transform.gameObject.tag == enemy)
                    {
                        enemySelected = true;
                        Debug.Log("engaging now." + enemy + "" + enemySelected);
                        //Set global variable to the selected enemy's tag. 
                        selectedEnemy = enemy;
                        chosenEnemy = hit.transform.gameObject;
                        target.transform.position = chosenEnemy.transform.position;

                    }
                    else if (hit.transform.gameObject.tag != enemy){enemySelected = false;}
                    
                
                }
               
            }
            
        }

The problem is, enemySelected is true only for a single frame, as the next frame overwrites it, I want it to be true UNTIL I click away. I was wondering what the best way to handle this would be?

How do you know it’s true for one frame? Your code most likely will reset the variable during the same frame. You iterate through all “enemyTitles” and “enemySelected” will only be true when the object you hit is the last item in that list / array. Because each iteration you either set your variable true or false. So say you have 5 items in your list and the object you hit is the 3rd item. When the loop gets to the 3rd element you set it to true. However when you continue iterating it will set it back to false at item 4 and 5 as it doesn’t match that name.

To select a single object you want to:

  • reset the variable to false “once” before you start the loop.
  • terminate the loop when you found a match.
  • Also you only need to do one raycast.

Something like that:

if (Input.GetMouseButtonDown(1))
{
    RaycastHit hit;
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    // reset it here
    enemySelected = false;
    if (Physics.Raycast(ray, out hit) && target != null)
    {
        target.transform.position = hit.point;
        foreach (string enemy in enemyTitles)
        {
            if (hit.transform.gameObject.tag == enemy)
            {
                enemySelected = true;
                // [ ... ]
                break; // stop the for loop
            }
            // [ ... ]