- Home /
Changing a bool on multiple instances of the same script
I have multiple enemies that use the same script in a scene and this script has a bool that will reset the enemy positions whenever the player enters a new room. I need this bool to be updated from a script attached to the door but I need to change the bool to be true on every instance of the script so every enemy is affected. I only know how to reference the script by mentioning the object it is attached too but this will only affect one instance. So is there an easy way to change every instance at once? Thank you!
little tricky with no script
public class YourBool : MonoBehaviour
{
public static bool variableName;
void Start()
{
variableName = true;
}
}
public class AnotherBool : MonoBehaviour
{
public bool anotherVariableName;
void Update()
{
if (YourBool.variableName)
{
anotherVariableName = true;
}
}
}
Answer by xibanya · Feb 27, 2021 at 07:13 AM
You could do away with the bool entirely and use event callbacks. Have your door have
public UnityEvent onReset;
Then in the inspector you'd be able to add callbacks like you can on UI buttons. You could drag all your enemies into here, then when you need everything to reset, call
onReset?.Invoke();
But maybe you don't want to drag your enemies into the slots in the inspector, or you instantiate new enemies at runtime. In that case, in your enemy script you could add
private static event Action onReset;
and a method
public static void InvokeReset()
{
onReset?.Invoke();
}
if you don't have one already, add a method
private void OnReset()
{
// your reset code here
}
and then in OnEnable, add
onReset += OnReset;
and in OnDisable add
onReset -= OnReset;
Then whenever you want all of your enemies to reset, have your door script (or any script) call EnemyClass.InvokeReset();