- Home /
Best way for me to deselect something once it's selected?
Hi, so I have a method that runs every frame. It deals with both selecting enemies and deselecting enemies through right-clicks. Right now it only works to select the enemy. Once you select one enemy the bool 'enemySelected' is true forever, even when you click elsewhere to deselect. What I need is for the bool to be true so long as the last right click was on an enemy.
public void SetTarget()
{
//Units will follow target psition.
//An array of selectable enemies.
enemyTitles = new string[5] { "Hoplite", "Archer", "Cavalry", "Peltast", "Slinger"};
if (target == null)
Debug.Log("Obviously something has gone wrong, target is null!");
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;
}
}
}
}
}
So originally I wanted to add an else statement after the last if statement, setting enemySelected to false. However, this doesn't work because the method is called next frame, leading to enemySelected equaling false. So what I want to know is how I would make this so that the method is called every frame, but is capable of deselecting for until I select an enemy and vice versa.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Select a boolean from an array 1 Answer
Boolean being overwritten 1 Answer
Multiple Cars not working 1 Answer