I have done the enemy chase script and the enemy spawner but everytime the enemies spawn in the chase the player but only 1 attacks.
Please help
I have done the enemy chase script and the enemy spawner but everytime the enemies spawn in the chase the player but only 1 attacks.
Please help
This is your problem: First, in your Chase script, you’ve declared
static Animator anim;
Then, in your Chase script’s Start event, you have
anim = GetComponent<Animator>();
A static variable is shared by all members of the class. This means that if you have a bunch of objects that have a Chase script on them, you will only have one anim variable that every instance of Chase is sharing. This is a good tool to use for some things, but this is a very bad tool to use when you have a bunch of objects with a script on them that holds a reference to another component on the object.
When each of these objects initialize, each Chase instance will try to set anim to its own animator, overwriting the animator of the previous instance to initialize, and so when everything is finished initializing, the anim variable will hold the Animator of whichever object was the last to initialize – and so each of your Chase scripts will have a reference to that last object’s animator instead of their own animator.
You can fix this by removing the static
keyword from your anim variable. This will cause each Chase script to have its own variable holding its own animator, instead of sharing one with all of them.
Side note: Did you get this from a tutorial somewhere? I’ve seen several other people do the exact same thing and I’d like to figure out whoever’s teaching people this and tell them to stop teaching people bad code.