Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by jeyemsss · Jun 24, 2021 at 11:36 AM · prefabenemy healthenemydamage

If one prefab enemy dies, the other enemy prefabs malfunction

MissingReferenceException: The object of type 'EnemyHealth' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. EnemyHealth.Die () (at Assets/Scripts/Enemy/EnemyHealth.cs:33) EnemyHealth.TakeDamage (System.Int32 damage) (at Assets/Scripts/Enemy/EnemyHealth.cs:26) PlayerCombat.Attack () (at Assets/PlayerCombat.cs:53) PlayerCombat.Update () (at Assets/PlayerCombat.cs:37)

So when I attack a prefab enemy and one of those prefab reach a health of 0 and destroys their game, the other enemies' health script from the prefab malfunctions, even though they didn't get destroyed.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class EnemyHealth : MonoBehaviour
 {
     public int enemy_maxHealth = 100;
     int enemy_currentHealth;
 
     public Enemy_Healthbar enemy_HB;
 
     void Start()
     {
         enemy_currentHealth = enemy_maxHealth;
         enemy_HB.EnemySetMaxHealth(enemy_maxHealth);
     }
 
     public void TakeDamage(int damage)
     {
         enemy_currentHealth -= damage;
 
         enemy_HB.EnemySetHealth(enemy_currentHealth);
 
         if(enemy_currentHealth <= 0)
         {
             Die();
         }
     }
 
     void Die()
     {
         Debug.Log("this mf dead");
         Destroy(gameObject);
     }
 
 }
 

This is for the Enemy AI, which instructs the enemy to attack the player and deal damage to the player, might be helpful if I put it in here as well.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class EnemyAI : MonoBehaviour
 {
     #region Public Variables
     public Transform rayCast;
     public LayerMask raycastMask;
     public float rayCastLength;
     public float attackDistance; //Minimum distance
     public float moveSpeed;
     public float timer; //Cooldown of attacks
     public Transform leftLimit;
     public Transform rightLimit;
 
     public int AttackDamage;
     public Transform triggerArea;
     public LayerMask Player;
     #endregion
 
     #region Private Variables
     private RaycastHit2D hit;
     private Transform target;
     private Animator animator;
     private float distance; //store distance between enemy and player
     private bool attackMode;
     private bool inRange; //See if player in range
     private bool cooling; //check if enemy is cooling after attack
     private float intTimer;
     private PlayerHealth playerHS;
     #endregion 
  
     void Awake()
     {
         SelectTarget();
         intTimer = timer;
         animator = GetComponent<Animator>();
         playerHS = GetComponent<PlayerHealth>();
     }
 
     // Update is called once per frame
     void Update()
     {
         if (!attackMode)
         {
             Move();
         }
 
         if (!InsideofLimits() && !inRange && !animator.GetCurrentAnimatorStateInfo(0).IsName("enemy1Attack"))
         {
             SelectTarget();
         }
 
         if (inRange)
         {
             hit = Physics2D.Raycast(rayCast.position, transform.right, rayCastLength, raycastMask);
             RaycastDebugger();
         }
 
         //When player is detected
         if (hit.collider != null)
         {
             EnemyLogic();
         }
         else if (hit.collider == null)
         {
             inRange = false;
         }
 
         if (inRange == false)
         {
             StopAttack();
         }
     }
 
     void OnTriggerEnter2D(Collider2D trig)
     {
         if (trig.gameObject.tag == "Player")
         {
             target = trig.transform;
             inRange = true;
             Flip();
         }
     }
 
     void EnemyLogic()
     {
         distance = Vector2.Distance(transform.position, target.position);
 
         if (distance > attackDistance)
         {
             StopAttack();
         }
         else if (attackDistance >= distance && cooling == false)
         {
             Attack();
         }
 
         if (cooling)
         {
             Cooldown();
             animator.SetBool("Attack", false);
         }
     }
 
     void Move()
     {
         animator.SetBool("Run", true);
 
         if (!animator.GetCurrentAnimatorStateInfo(0).IsName("enemy1Attack"))
         {
             Vector2 targetPosition = new Vector2(target.position.x, transform.position.y);
 
             transform.position = Vector2.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
 
         }
     }
 
     void Attack()
     {
         timer = intTimer;
         attackMode = true;
 
         animator.SetBool("Run", false);
         animator.SetBool("Attack", true);
         hit.collider.gameObject.GetComponent<PlayerHealth>().TakeDamage(AttackDamage);
 
     }
 
     void Cooldown()
     {
         timer -= Time.deltaTime;
 
         if (timer <= 0 && cooling && attackMode)
         {
             cooling = false;
             timer = intTimer;
         }
     }
 
     void StopAttack()
     {
         cooling = false;
         attackMode = false;
         animator.SetBool("Attack", false);
     }
 
     void RaycastDebugger()
     {
         if (distance > attackDistance)
         {
             Debug.DrawRay(rayCast.position, transform.right * rayCastLength, Color.red);
         }
         else if (attackDistance > distance)
         {
             Debug.DrawRay(rayCast.position, transform.right * rayCastLength, Color.green);
         }
     }
 
     public void TriggerCooling()
     {
         cooling = true;
     }
 
     private bool InsideofLimits()
     {
         return transform.position.x > leftLimit.position.x && transform.position.x < rightLimit.position.x;
     }
 
     private void SelectTarget()
     {
         float distanceToLeft = Vector2.Distance(transform.position, leftLimit.position);
         float distanceToRight = Vector2.Distance(transform.position, rightLimit.position);
 
         if (distanceToLeft > distanceToRight)
         {
             target = leftLimit;
         }
         else
         {
             target = rightLimit;
         }
     }
 
     private void Flip()
     {
         Vector3 rotation = transform.eulerAngles;
         if (transform.position.x > target.position.x)
         {
             rotation.y = 180f;
         }
         else
         {
             rotation.y = 0f;
         }
 
         transform.eulerAngles = rotation;
     }
 }
 


Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

198 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

duplicating enemies not working correctly 1 Answer

Unity Network Spawning Prefabs 0 Answers

Problem with exe - Sprites don't display correctly 1 Answer

How to make another ground spawn beneath itself 1 Answer

[Unity 2018.3.0b3] Prefab loss reference to child objects when moved to scene 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges