helloo. so I have a script on multiple enemies each with their own health. I want to make a <button> that, when pressed will set all enemy’s health to 0.
public class EnemiesWithHealth: MonoBehaviour
{
public float health;
void Update(){}
void Start(){}
public void KillAll() //for the button
{
health = 0;
}
}
I dragged in one of the enemy’s gameobject into the button and assigned the KillAll() function to it but when I press the button, it only sets the enemy I dragged into the button’s health to zero, not all of them.
EDIT: I’ve added the code for doing it through script.
First of all, create a new tag “KillButton”, and assign it to the Button. This way, each enemy can Find the Button by searching for its tag.
Here’s the code:
using UnityEngine;
using UnityEngine.UI;
public class EnemiesWithHealth : MonoBehaviour {
public float health;
private Button killButton;
void Awake()
{
killButton = GameObject.FindGameObjectWithTag("KillButton").GetComponent<Button>();
}
private void OnEnable()
{
killButton.onClick.AddListener(KillAll);
}
private void OnDisable()
{
killButton.onClick.RemoveListener(KillAll);
}
void Update()
{
}
void Start()
{
}
public void KillAll() //for the button
{
health = 0;
}
}
You’ll have to collect all the instances of the class and one by one call the function you want. You can use FindObjectsOfType() (which is expensive) or if you have tagged the enemy the script is on, FindGameObjectsWithTag(). So your button should call from a different script the method KillAll(), which in turn calls Kill() and implements a logic that looks like this:
public void KillAll(){
EnemiesWithHealth[] enemiesScript = FindObjectsOfType<EnemiesWithHealth>();
for(int i = 0;i <enemiesScript.Length;i++){
enemiesScript*.Kill();*
} } OR public void KillAll(){ GameObject[] enemies = GameObject.FindGameObjectsWithTag(“Enemy”); for(int i = 0;i <enemies.Length;i++){ enemies*.GetComponent().Kill();* } }