Search code examples
c#unity-game-engineinstanceanimator

Instances of prefab aren't being controlled separately


I have multiple enemies set up in a level, all using the same behaviour and animator scripts. When I hit or kill one of them, all of them get hit or killed. I need them to function as separate instances.

I have tried referencing only an instance of the script:

 private GoblinBehaviour goblin;
  goblin = GetComponent<GoblinBehaviour>();
        goblin.IncrementHits(1);

But that doesn't work. An error arises that says that script can't be accessed with an instance and needs a type instead.

code for hit detection script:

   public class RangedDetection : MonoBehaviour
   {
   private GoblinBehaviour goblin;
   void OnTriggerEnter(Collider other)
    {
    //on colliding destroy rocks after its life time
    Destroy(gameObject, rockLifeTime);

    if (other.gameObject.tag.Equals("Enemy"))
    //if (other.tag == "Enemy")
    {
        Destroy(other.gameObject);
    }
    else if (other.gameObject.tag.Equals("Goblin"))//goblin should play 
 death animation
    {
       goblin = GetComponent<GoblinBehaviour>();
        goblin.IncrementHits(1);
        GetComponent<BoxCollider>().enabled = false; //Removing hit 
 collider so it only hits target once.
    }
 }
 }

Simplified Code for goblin script:

 public class GoblinBehaviour : MonoBehaviour
 {
Transform player;

public static bool isDead;
public static bool isPunching;
public static bool isHit;
public GameObject particles;
public Animator anim;


 public void IncrementHits(int hitCount)
 {
    isHit = true;
    hits += hitCount;
    if (hits >= 2) isDead = true;


}

void Die()
{
    Instantiate(particles, transform.position, transform.rotation);
    Destroy(gameObject);

}


void updateAnim()
{
    anim.SetBool("Punch_b", isPunching);
    anim.SetBool("hit", isHit);

}

}

Things should animate and act separately, I'm not sure how to reference only the current instance of the script.


Solution

  • While your code is incomplete and the problem cannot be said for sure, it looks like you are using statics improperly.

    Static properties are instance analagous. In other words, all of your goblin instances share any static properties (isPunching, isHit, isDead, etc.). Making these values static allows you to reference them directly without having to obtain the instance you're affecting, but results in you updating all goblins at once.

    Your solution will involve removing the static modifier from your GoblinBehaviour properties unless the properties are meant to be shared across all instances.