In my game, you jump on zombies'heads to squash them.
Currently I'm only able to have one zombie in my game. When I add another (duplicate or drag from prefab), then run the game, I can squash one enemy but when I try to jump on the second zombie's head it says "Coroutine couldn't be started because the game object "Zombie (1)" is inactive".
Here's the player's stompbox script code & below that the ZombieController script code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StompEnemy : MonoBehaviour {
private Rigidbody2D playerRigidbody;
public ZombieController zombieController;
public float bounceForce;
// a bounce force of 12 is wonderful (set in unity's inspector)
// Use this for initialization
void Start () {
playerRigidbody = transform.parent.GetComponent<Rigidbody2D>();
zombieController = FindObjectOfType<ZombieController>();
}
// Update is called once per frame
void Update () {
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Zombie")
{
zombieController.Stomped();
playerRigidbody.velocity = new Vector2(playerRigidbody.velocity.x, bounceForce);
}
}
}
Now here's the ZombieController script code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ZombieController : MonoBehaviour {
Animator zombieAnimator;
Rigidbody2D myRigidBody;
[SerializeField] float moveSpeed = 1f;
public bool isAlive = true;
// Use this for initialization
void Start () {
zombieAnimator = GetComponent<Animator>();
myRigidBody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
if (!isAlive) { return; }
if (isFacingRight())
{
myRigidBody.velocity = new Vector2(moveSpeed, 0f);
}
else
{
myRigidBody.velocity = new Vector2(-moveSpeed, 0f);
}
}
bool isFacingRight()
{
return transform.localScale.x > 0;
// if it's positive he's facing right, and if negative, facing left.
}
private void OnTriggerExit2D(Collider2D collision)
{
transform.localScale = new Vector2(-(Mathf.Sign(myRigidBody.velocity.x)), 1f);
}
public void Stomped()
{
isAlive = false;
transform.localScale = new Vector2(-(Mathf.Sign(myRigidBody.velocity.x)), 1f);
zombieAnimator.SetBool("Squash", true);
if (isFacingRight())
{
myRigidBody.velocity = new Vector2(Mathf.Epsilon, 0f);
}
else if (!isFacingRight())
{
myRigidBody.velocity = new Vector2(-Mathf.Epsilon, 0f);
}
gameObject.layer = 11;
StartCoroutine(WaitXSecond());
}
public IEnumerator WaitXSecond()
{
yield return new WaitForSeconds(2f);
gameObject.SetActive(false);
zombieAnimator.SetBool("Squash", false);
}
}
How do I implement multiple zombies using the same script attached to each one?
When I've tried having three zombies I'd jump on the first one's head and another zombie would die (show the squashed animation, then disappear after two seconds) and the remaining zombies would no longer be jump-on-head-able, displaying the coroutine error above.