- Home /
Select an enemy to attack with buttons?
Hello!
I have an array of enemy objects and an Attack Button that executes Attack() on click. When I press my attack button, I would like another select button to appear above the first enemy in my enemy array and then when I press right or left it will go to the next enemy so that I can choose who to attack. I can't seem to come up with a way to implement this. My brain is fried over this, so any help would be GREATLY appreciated! :)
Answer by Dragondean · Jul 22, 2020 at 04:50 AM
I would assume that each enemy is part of an array. If so we create an int identifying which array piece is selected. so for instance:
enemytype[] enemies;
int selectedEnemy;
Then we use a keycode to detect input. If it is left, we check if there is an enemy one down the array, if not cycle it back up. Vice versa with the right side.
if (Keycode.whateverkeyisleft){
if (enemies[selectedEnemy-1] != null){
selectedEnemy = enemies[selectedEnemy-1];
} else {
selectedEnemy = enemies[enemies.length-1];
}
}
if (Keycode.whateverkeyisRight){
if (enemies[selectedEnemy+1] != null){
selectedEnemy = enemies[selectedEnemy+1];
} else {
selectedEnemy = enemies[0];
}
}
Then, by combining those two pieces of code, the selected enemy will change based upon input.
That is a pretty good idea. But wouldn't it not work if you were on the left most enemy and press left? example: Enemy 0 > Press Left > Enemy -1 instead of the right most enemy? In other words, rather than going to the last element in the array, wouldn't it would go to -1 which doesn't exist? Similar situation with right.
Also, is there anyway to make the selector a UIButton? If possible, I'd like the button to start on enemy[0] and then move from enemy to enemy with left and right presses. When the selector UIButton is hovered an enemy, i'd like them to be the current selectedEnemy.
Thanks again for the response!
if you look closely, you will see that I did not use $$anonymous$$us 1 if left returned null. I took the array of enemies and then subtracted one to get the last element in the array. Look at the if else statement I put; it checks if there is an enemy to the left (the null statement) and then it runs different functions depending on if it was returned null, so as previously explained when it returns null it gets the array length and then subtracts one (you have to subtract one to get the last element).
With the ui button, you can create a public gameobject and then get the position of the enemy with selectedenemy.transform.position. Set the buttons position to that exact position. Then just add as much offset as you want with new Vector2(transform.position.x + offsetx, transform.position.y + offset y).
PS be sure your canvas is set to world space in render mode (see here for more info (https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/UICanvas.html))
Answer by Payaso_Prince · Jul 22, 2020 at 02:43 AM
If it makes things clearer, here is what I am going for.