Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 /
avatar image
0
Question by MythicEclipsed · Jul 25, 2016 at 06:02 AM · scripting problemscripting beginner

Help! This script is causing my Enemy to die on Spawn??

Hello,

I have been having issues with a simple script, it seems to be causing my enemies to die on spawn please help, am new to coding. using UnityEngine; using System.Collections;

 public class DamageHandlerEnemy : MonoBehaviour {
 
     public int maxHealth = 100;
 
     [System.Serializable]
     public class EnemyStats {
     public int maxHealth;
 
     private int _curHealth;
     public int curHealth 
     {
         get { return _curHealth; }
         set { _curHealth = Mathf.Clamp (value, 0, maxHealth); }
     }
 
         public void Init()
         {
             curHealth = maxHealth;
         }
 }
 
     public float invulnPeriod = 0;
     float invulnTimer = 0;
     int correctLayer;
 
     SpriteRenderer spriteRend;
 
     public EnemyStats stats = new EnemyStats ();
 
     [Header ("Optional: ")]
     [SerializeField]
     private StatusIndicator statusIndicator;
     void Start() {
         correctLayer = gameObject.layer;
 
         // NOTE!  This only get the renderer on the parent object.
         // In other words, it doesn't work for children. I.E. "enemy01"
         spriteRend = GetComponent<SpriteRenderer>();
 
         if(spriteRend == null) {
             spriteRend = transform.GetComponentInChildren<SpriteRenderer>();
 
             if(spriteRend==null) {
                 Debug.LogError("Object '"+gameObject.name+"' has no sprite renderer.");
 
                 stats.Init();
 
                 if (statusIndicator != null) 
                 {
                     statusIndicator.SetHealth (stats.curHealth, stats.maxHealth);
                 }
             
             }
         }
     }
 
     void OnTriggerEnter2D() {
         EnemyStats stats = new EnemyStats ();
         stats.curHealth--;
 
         if(invulnPeriod > 0) {
             invulnTimer = invulnPeriod;
             gameObject.layer = 10;
         }
     }
 
     void Update() {
 
         if(invulnTimer > 0) {
             invulnTimer -= Time.deltaTime;
 
             if(invulnTimer <= 0) {
                 gameObject.layer = correctLayer;
                 if(spriteRend != null) {
                     spriteRend.enabled = true;
                 }
             }
             else {
                 if(spriteRend != null) {
                     spriteRend.enabled = !spriteRend.enabled;
                 }
             }
         }
 
         EnemyStats stats = new EnemyStats ();
 
         if(stats.curHealth <= 0) {
             Die();
         
             if (statusIndicator != null) 
             {
                 statusIndicator.SetHealth (stats.curHealth, stats.maxHealth);
             }
         
         }
     }
 
     void Die() {
         Destroy(gameObject);
     }
 
 }
 
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

2 Replies

· Add your reply
  • Sort: 
avatar image
3
Best Answer

Answer by ScaniX · Jul 25, 2016 at 08:37 AM

I think the line 85 is there by accident:

 85: EnemyStats stats = new EnemyStats ();

You already have an instance in your member variable that got initialized in your Start() method. I cannot see why you would want to create a local variable with a new instance here. :)

The same goes for the same code line in your OnTriggerEnter2D() method.

Also: You are never setting your maxHealth member in the EnemyStats class. You have a member in the outer class that is set to 100, but the member of the stats class stays 0.

You should probably just create ONE constant in the outer class like this:

 public static int maxHealth = 100; // or const if it is never changed from somewhere

And then use it everywhere with

 DamageHandlerEnemy.maxHealth








Comment
Add comment · Show 1 · Share
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
avatar image Naphier · Jul 25, 2016 at 08:42 AM 0
Share

Also that OnTriggerEnter2D has no filter, so anything entering the trigger area is going to reduce the enemies health. ick.

avatar image
0

Answer by tanoshimi · Jul 25, 2016 at 06:09 AM

Float values are initialised to zero by default. Therefore your problem is here:

 EnemyStats stats = new EnemyStats (); 
 if(stats.curHealth <= 0) { 
   Die();

Unless your constructor states otherwise, the curHealth value of your newly-created stats class is 0. So you're destroying the gameobject immediately after.

Comment
Add comment · Show 1 · Share
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
avatar image saschandroid · Jul 25, 2016 at 08:42 AM 0
Share

Yes. And even after changing the value in the constructor you should not call 'EnemyStats stats = new EnemyStats ();' right before checking the curHealth in the Update()-function ... as the value will always be the one of the constructor in the next line (87) and 'stats.curHealth

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

6 People are following this question.

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

Related Questions

Counting prefabs in screen?,Problem with counting prefabs in screen 1 Answer

how to allow the key to only open 1 door rather than all of them? 0 Answers

(PLEASE HELP) hi guys! i have a problem with my Score text 1 Answer

First Person Controller - Problems with footstep audio being played too fast. 0 Answers

Iterate through area descibed by objects 1 Answer


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