Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Enemy health

Discussion in 'Scripting' started by JaimieVos, Apr 5, 2016.

  1. JaimieVos

    JaimieVos

    Joined:
    Jun 21, 2015
    Posts:
    193
    Enemy script:
    Code (csharp):
    1.  
    2.  
    3. using UnityEngine;
    4. using System.Collections;
    5. using UnityEngine.UI;
    6.  
    7. public class Enemy:MonoBehaviour{
    8.  
    9. //------------Variables----------------//
    10. private Transform target;
    11. public int moveSpeed;
    12. public int rotationSpeed;
    13. public int maxdistance;
    14. private GameObject PlayerTarget;
    15. public float enemyHealth=100f;
    16. private bool attack;
    17. private bool movement;
    18. private float attackTimer;
    19. private float cooldown;
    20. private Animator myAnimator;
    21. private Transform myTransform;
    22. public int health;
    23.  
    24. Text healthText;
    25. //------------------------------------//
    26.  
    27. public Player playerScript;
    28.  
    29. void Awake()
    30. {
    31. myTransform=transform;
    32. }
    33.  
    34.  
    35. void Start()
    36. {
    37. health=100;
    38. myAnimator=GetComponent<Animator>();
    39. maxdistance=2;
    40. movement=true;
    41. attackTimer=0;
    42. cooldown=1.0f;
    43. healthText=GetComponent<Text>();
    44. target=GameObject.FindGameObjectWithTag("Player").transform;
    45. PlayerTarget=GameObject.FindGameObjectWithTag("Player");
    46. }
    47.  
    48.  
    49. void Update()
    50. {
    51. if(Vector3.Distance(target.position, myTransform.position) > maxdistance&&movement==true)
    52. {
    53. //Getadirectionvectorfromustothe target
    54. Vector3dir=target.position-myTransform.position;
    55.  
    56. //Normalizeitsothatit'saunitdirection vector
    57. dir.Normalize();
    58.  
    59. //Moveourselvesinthat direction
    60. myTransform.position+=dir*moveSpeed*Time.deltaTime;
    61. }
    62.  
    63. if(attackTimer>0)
    64. {
    65. attackTimer-=Time.deltaTime;
    66. }
    67. if(attackTimer<0)
    68. {
    69. attackTimer=0;
    70. }
    71.  
    72. Flip();
    73. EnemyHealth();
    74. ResetValues();
    75. }
    76.  
    77. private void EnemyHealth()
    78. {
    79. if(enemyHealth<=0)
    80. {
    81. Destroy(gameObject);
    82. }
    83. }
    84.  
    85.  
    86. private void Flip()
    87. {
    88. Vector2sides=Vector2.right;
    89. Vector2playerPosistion=target.transform.position-transform.position;
    90.  
    91. if(Vector2.Dot(sides,playerPosistion)<0){
    92. Vector3theScale=transform.localScale;
    93.  
    94. theScale.x=-1;
    95.  
    96. transform.localScale=theScale;
    97. }
    98. else{
    99. Vector3theScale=transform.localScale;
    100.  
    101. theScale.x=1;
    102.  
    103. transform.localScale=theScale;
    104. }
    105. }
    106.  
    107. void OnCollisionEnter2D(Collision2D col)
    108. {
    109. if(col.gameObject.name=="Player")
    110. {
    111. if(attackTimer==0)
    112. {
    113. attackTimer=cooldown;
    114. movement=false;
    115. myAnimator.SetTrigger("attack");
    116. }
    117. }
    118. }
    119.  
    120. void OnCollisionExit2D(Collision2D col)
    121. {
    122. if(col.gameObject.Equals(PlayerTarget))
    123. {
    124. movement=true;
    125. }
    126. }
    127.  
    128. void ResetValues()
    129. {
    130. attack=false;
    131. }
    132. }
    133.  
    Player script:
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using UnityEngine.UI;
    5.  
    6. publicclassPlayer:MonoBehaviour{
    7.  
    8. private Rigidbody2D rb2d;
    9.  
    10. private Animator myAnimator;
    11.  
    12. [SerializeField]
    13. private float movementSpeed;
    14.  
    15. private bool attack;
    16.  
    17. [SerializeField]
    18. private Text infoText;
    19.  
    20. private bool facingRight;
    21.  
    22. [SerializeField]
    23. private Transform[] groundPoints;
    24.  
    25. [SerializeField]
    26. private GameObject rigidbody;
    27.  
    28. [SerializeField]
    29. private float groundRadius;
    30.  
    31. privatefloatattackTimer;
    32. private float cooldown;
    33.  
    34. public Enemy enemyScript;
    35.  
    36. [SerializeField]
    37. private LayerMask whatIsGround;
    38.  
    39. private bool isGrounded;
    40.  
    41. private bool jump;
    42.  
    43. public float Health=50f;
    44.  
    45. [SerializeField]
    46. private float jumpForce;
    47.  
    48. private bool attacking;
    49.  
    50. void Start()
    51. {
    52. Health=50f;
    53. facingRight=true;
    54. rb2d=rigidbody.GetComponent<Rigidbody2D>();
    55. myAnimator=GetComponent<Animator>();
    56. attackTimer=0;
    57. cooldown=1.0f;
    58. }
    59.  
    60. void Update()
    61. {
    62. HandleInput();
    63.  
    64. if(attackTimer>0)
    65. {
    66. attackTimer-=Time.deltaTime;
    67. }
    68. if(attackTimer<0)
    69. {
    70. attackTimer=0;
    71. }
    72. }
    73.  
    74. void FixedUpdate()
    75. {
    76. floathorizontal=Input.GetAxis("Horizontal");
    77.  
    78. isGrounded=IsGrounded();
    79.  
    80. HandleMovement(horizontal);
    81.  
    82. Flip(horizontal);
    83.  
    84. HandleAttacks();
    85.  
    86. playerHealth();
    87.  
    88. ResetValues();
    89. }
    90.  
    91. private void playerHealth()
    92. {
    93. if(Health<=0)
    94. {
    95. Debug.Log("dood");
    96. Time.timeScale=0;
    97. }
    98. }
    99.  
    100. private void HandleMovement(float horizontal)
    101. {
    102. if(!this.myAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack"))
    103. {
    104. rb2d.velocity=newVector2(horizontal*movementSpeed,rb2d.velocity.y);
    105. }
    106.  
    107. if(isGrounded&&jump)
    108. {
    109. isGrounded=false;
    110. rb2d.AddForce(newVector2(0,jumpForce));
    111. }
    112.  
    113. rb2d.velocity=newVector2(horizontal*movementSpeed,rb2d.velocity.y);
    114.  
    115. myAnimator.SetFloat("speed",Mathf.Abs(horizontal));
    116. }
    117.  
    118. private void HandleAttacks()
    119. {
    120. if(attack&& !this.myAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack"))
    121. {
    122. myAnimator.SetTrigger("attack");
    123. rb2d.velocity=Vector2.zero;
    124. }
    125. }
    126.  
    127. private void HandleInput()
    128. {
    129. if(Input.GetKeyDown(KeyCode.LeftShift))
    130. {
    131. attack=true;
    132. attacking=true;
    133. }
    134.  
    135. if(Input.GetKeyDown(KeyCode.Space))
    136. {
    137. jump=true;
    138. }
    139. }
    140.  
    141. private void Flip(float horizontal)
    142. {
    143. if(horizontal>0&& !facingRight || horizontal<0&&facingRight)
    144. {
    145. facingRight= !facingRight;
    146.  
    147. Vector3theScale=transform.localScale;
    148.  
    149. theScale.x*=-1;
    150.  
    151. transform.localScale=theScale;
    152. }
    153. }
    154.  
    155. private void ResetValues()
    156. {
    157. attack=false;
    158. jump=false;
    159. //attacking=false;
    160. }
    161.  
    162. private bool IsGrounded()
    163. {
    164. if(rb2d.velocity.y<=0)
    165. {
    166. foreach(Transform point ingroundPoints)
    167. {
    168. Collider2D[]colliders=Physics2D.OverlapCircleAll(point.position,groundRadius,whatIsGround);
    169.  
    170. for(inti=0;i<colliders.Length;i++)
    171. {
    172. if(colliders[i].gameObject !=gameObject)
    173. {
    174. return true;
    175. }
    176. }
    177. }
    178. }
    179. return false;
    180. }
    181.  
    182. void OnCollisionEnter2D(Collision2D col)
    183. {
    184. if(col.gameObject.CompareTag("Enemy"))
    185. {
    186. if(attackTimer==0)
    187. {
    188. attackTimer=cooldown;
    189. Health-=5f;
    190. infoText.text="Health:"+Health;
    191. }
    192. }
    193.  
    194. if(col.gameObject.CompareTag("Enemy"))
    195. {
    196. if(attacking==true)
    197. {
    198. attacking=false;
    199. enemyScript.enemyHealth-=50;
    200. }
    201. }
    202. }
    203. }
    204.  
    Spawner:
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public classSpawner:MonoBehaviour{
    6.  
    7. private float spawnTimer;
    8. private float cooldown;
    9.  
    10. public GameObject[] spawnpoints;
    11. GameObject currentPoint;
    12. int index;
    13.  
    14. public GameObject[] Enemys;
    15. GameObject currentenemy;
    16. int indexenemy;
    17.  
    18. void Start()
    19. {
    20. spawnTimer=0;
    21. cooldown=5f;
    22. }
    23.  
    24. void Update(){
    25. if(spawnTimer>0)
    26. {
    27. spawnTimer-=Time.deltaTime;
    28. }
    29. if(spawnTimer<0)
    30. {
    31. spawnTimer=0;
    32. }
    33.  
    34. if(spawnTimer==0)
    35. {
    36. spawnTimer=cooldown;
    37. spawnTimer-=0.5f;
    38. index=Random.Range(0,spawnpoints.Length);
    39. currentPoint=spawnpoints[index];
    40.  
    41. indexenemy=Random.Range(0,Enemys.Length);
    42. currentenemy=Enemys[indexenemy];
    43.  
    44. Instantiate(currentenemy,currentPoint.transform.position,currentPoint.transform.rotation);
    45. }
    46. }
    47. }
    48.  
    The enemy's run to the player but when the player hits them they stop running and they are standing.
    When i hit the enemy 2 times he don't die? And the health randomly goes to -300 in the prefab or something during the game and then they cant spawn anymore with the spawner?
     
    Last edited: Apr 6, 2016
  2. CrymX

    CrymX

    Joined:
    Feb 16, 2015
    Posts:
    179
    Your code ins unreadable, can you please make a better copy paste ?
     
  3. Josenifftodd

    Josenifftodd

    Joined:
    Nov 29, 2013
    Posts:
    158
    Your code is terribly formatted, i guess you've copied and pasted it off a site, I also don't why you have EnemyHealth and Health or why you set health to 100 if enemyHealth is already at 100f.... from what I can read your not telling it which Enemy to destroy... lol.


    Code (CSharp):
    1. privatevoidEnemyHealth()
    2. {
    3. if(enemyHealth<=0)
    4. {
    5. Destroy(this);
    6. }
    7. }
    Format your code like this:


    Code (CSharp):
    1. private void EnemyHealth(){
    2. if(enemyHealth<=0) {
    3.          Destroy(this);
    4.    }
    5. }
     
  4. Hyblademin

    Hyblademin

    Joined:
    Oct 14, 2013
    Posts:
    725
    this is a reference to the instance of the class described by the script. OP already had Destroy(gameObject) which is a reference to the GameObject the object is attached to.

    I agree with the formatting issue, please use indentation. Whether to put opening braces '{' on the same line or the next line is up to you.

    Code (CSharp):
    1. private void EnemyHealth()
    2. {
    3.  
    4.     if(enemyHealth<=0)
    5.     {
    6.          Destroy(gameObject);
    7.     }
    8.  
    9. }
    10.  
    11. //This is fine
    12.  
    13. ...
    14.  
    15. private void EnemyHealth() {
    16.  
    17.     if(enemyHealth<=0) {
    18.          Destroy(gameObject);
    19.     }
    20.  
    21. }
    22.  
    23. //Also fine
     
    Last edited: Apr 6, 2016
  5. JaimieVos

    JaimieVos

    Joined:
    Jun 21, 2015
    Posts:
    193
    Edited
     
  6. JaimieVos

    JaimieVos

    Joined:
    Jun 21, 2015
    Posts:
    193
    Yes i know thats both fine :D. But the biggest problem is that the enemy stop moving when they collides the player.
     
  7. Hyblademin

    Hyblademin

    Joined:
    Oct 14, 2013
    Posts:
    725
    Code (CSharp):
    1. if(Vector3.Distance(target.position, myTransform.position) > maxdistance&&movement==true)
    2.  
    3. ...
    Your enemy's movement on line 60 is wrapped in the above conditional. Notice that it requires movement to be true to run, however movement is set to false within OnCollisionEnter2D() if attackTimer is 0 (line 114). If you want the enemy to move again, you'll need to reset movement to true somewhere, or stop it from being set as false at line 114. Not 100% sure what the logic is supposed to be, but you probably will know which one you need to do for your game.
     
  8. JaimieVos

    JaimieVos

    Joined:
    Jun 21, 2015
    Posts:
    193
    Im setting it on true here:
    Code (csharp):
    1.  
    2.   voidOnCollisionExit2D(Collision2Dcol)
    3. {
    4. if(col.gameObject.Equals(PlayerTarget))
    5. {
    6. movement=true;
    7. }
    8. }
    9.  
     
  9. Hyblademin

    Hyblademin

    Joined:
    Oct 14, 2013
    Posts:
    725
    Can you confirm that movement is being set to true as expected using print()? Can you confirm that all the other conditions on line 51 are still true after colliding using print()?

    I also noticed on line 51 that you're checking for a distance to be greater than a variable called 'maxDistance'. In other words, it will only move toward the player if it is over 2 units away. Is that what you wanted, rather than only chase the player when it is closer than 2 units?
     
  10. JaimieVos

    JaimieVos

    Joined:
    Jun 21, 2015
    Posts:
    193
    I have 2 problems left now:
    The enemy's stop moving after colliding with the player and the player can't die. I maked this now:

    Enemy:
    Code (csharp):
    1.  
    2.   //------------Variables----------------//
    3. privateTransformtarget;
    4. publicintmoveSpeed;
    5. publicintrotationSpeed;
    6. publicintmaxdistance;
    7. privateGameObjectPlayerTarget;
    8. publicfloatenemyHealth=100f;
    9. privateboolattack;
    10. privateboolmovement;
    11. privatefloatattackTimer;
    12. privatefloatcooldown;
    13. privateAnimatormyAnimator;
    14. privateTransformmyTransform;
    15. privateboolattacking;
    16.  
    17. TexthealthText;
    18. //------------------------------------//
    19.  
    20. publicPlayerplayerScript;
    21.  
    22. voidAwake()
    23. {
    24. myTransform=transform;
    25. }
    26.  
    27.  
    28. voidStart()
    29. {
    30. myAnimator=GetComponent<Animator>();
    31. maxdistance=2;
    32. movement=true;
    33. attackTimer=0;
    34. cooldown=1.0f;
    35. healthText=GetComponent<Text>();
    36. target=GameObject.FindGameObjectWithTag("Player").transform;
    37. PlayerTarget=GameObject.FindGameObjectWithTag("Player");
    38. }
    39.  
    40.  
    41. voidUpdate()
    42. {
    43. if(Vector3.Distance(target.position,myTransform.position)>maxdistance&&movement==true)
    44. {
    45. //Getadirectionvectorfromustothe target
    46. Vector3dir=target.position-myTransform.position;
    47.  
    48. //Normalizeitsothatit'saunitdirection vector
    49. dir.Normalize();
    50.  
    51. //Moveourselvesinthat direction
    52. myTransform.position+=dir*moveSpeed*Time.deltaTime;
    53. }
    54.  
    55. if(attackTimer>0)
    56. {
    57. attackTimer-=Time.deltaTime;
    58. }
    59. if(attackTimer<0)
    60. {
    61. attackTimer=0;
    62. }
    63.  
    64. if(Input.GetKeyDown(KeyCode.LeftShift))
    65. {
    66. attacking=true;
    67. }
    68.  
    69. Flip();
    70. EnemyHealth();
    71. ResetValues();
    72. }
    73.  
    74. privatevoidEnemyHealth()
    75. {
    76. if(enemyHealth<=0)
    77. {
    78. Destroy(gameObject);
    79. }
    80. }
    81.  
    82.  
    83. privatevoidFlip()
    84. {
    85. Vector2sides=Vector2.right;
    86. Vector2playerPosistion=target.transform.position-transform.position;
    87.  
    88. if(Vector2.Dot(sides,playerPosistion)<0){
    89. Vector3theScale=transform.localScale;
    90.  
    91. theScale.x=-1;
    92.  
    93. transform.localScale=theScale;
    94. }
    95. else{
    96. Vector3theScale=transform.localScale;
    97.  
    98. theScale.x=1;
    99.  
    100. transform.localScale=theScale;
    101. }
    102. }
    103.  
    104. voidOnCollisionEnter2D(Collision2Dcol)
    105. {
    106. if(col.gameObject.name=="Player")
    107. {
    108. if(attackTimer==0)
    109. {
    110. attackTimer=cooldown;
    111. movement=false;
    112. myAnimator.SetTrigger("attack");
    113. }
    114. }
    115.  
    116. if(col.gameObject.CompareTag("Player"))
    117. {
    118. if(attacking==true)
    119. {
    120. attacking=false;
    121. enemyHealth-=50;
    122. }
    123. }
    124. }
    125.  
    126. voidOnCollisionExit2D(Collision2Dcol)
    127. {
    128. if(col.gameObject.Equals(PlayerTarget))
    129. {
    130. movement=true;
    131. }
    132. }
    133.  
    134. voidResetValues()
    135. {
    136. attack=false;
    137. }
    138. }
    139.  
    Player:
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using UnityEngine.UI;
    5.  
    6. publicclassPlayer:MonoBehaviour{
    7.  
    8. privateRigidbody2Drb2d;
    9.  
    10. privateAnimatormyAnimator;
    11.  
    12. [SerializeField]
    13. privatefloatmovementSpeed;
    14.  
    15. privateboolattack;
    16.  
    17. [SerializeField]
    18. privateTextinfoText;
    19.  
    20. privateboolfacingRight;
    21.  
    22. [SerializeField]
    23. privateTransform[]groundPoints;
    24.  
    25. [SerializeField]
    26. privateGameObjectrigidbody;
    27.  
    28. [SerializeField]
    29. privatefloatgroundRadius;
    30.  
    31. privatefloatattackTimer;
    32. privatefloatcooldown;
    33.  
    34. publicEnemyenemyScript;
    35.  
    36. [SerializeField]
    37. privateLayerMaskwhatIsGround;
    38.  
    39. privateboolisGrounded;
    40.  
    41. privatebooljump;
    42.  
    43. publicfloatHealth=50f;
    44.  
    45. [SerializeField]
    46. privatefloatjumpForce;
    47.  
    48. privateboolattacking;
    49.  
    50. voidStart()
    51. {
    52. Health=50f;
    53. facingRight=true;
    54. rb2d=rigidbody.GetComponent<Rigidbody2D>();
    55. myAnimator=GetComponent<Animator>();
    56. attackTimer=0;
    57. cooldown=1.0f;
    58. }
    59.  
    60. voidUpdate()
    61. {
    62. HandleInput();
    63.  
    64. if(attackTimer>0)
    65. {
    66. attackTimer-=Time.deltaTime;
    67. }
    68. if(attackTimer<0)
    69. {
    70. attackTimer=0;
    71. }
    72. }
    73.  
    74. voidFixedUpdate()
    75. {
    76. floathorizontal=Input.GetAxis("Horizontal");
    77.  
    78. isGrounded=IsGrounded();
    79.  
    80. HandleMovement(horizontal);
    81.  
    82. Flip(horizontal);
    83.  
    84. HandleAttacks();
    85.  
    86. playerHealth();
    87.  
    88. ResetValues();
    89. }
    90.  
    91. privatevoidplayerHealth()
    92. {
    93. if(Health<=0)
    94. {
    95. Debug.Log("dood");
    96. Time.timeScale=0;
    97. }
    98. }
    99.  
    100. privatevoidHandleMovement(floathorizontal)
    101. {
    102. if(!this.myAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack"))
    103. {
    104. rb2d.velocity=newVector2(horizontal*movementSpeed,rb2d.velocity.y);
    105. }
    106.  
    107. if(isGrounded&&jump)
    108. {
    109. isGrounded=false;
    110. rb2d.AddForce(newVector2(0,jumpForce));
    111. }
    112.  
    113. rb2d.velocity=newVector2(horizontal*movementSpeed,rb2d.velocity.y);
    114.  
    115. myAnimator.SetFloat("speed",Mathf.Abs(horizontal));
    116. }
    117.  
    118. privatevoidHandleAttacks()
    119. {
    120. if(attack&& !this.myAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack"))
    121. {
    122. myAnimator.SetTrigger("attack");
    123. rb2d.velocity=Vector2.zero;
    124. }
    125. }
    126.  
    127. privatevoidHandleInput()
    128. {
    129. if(Input.GetKeyDown(KeyCode.LeftShift))
    130. {
    131. attack=true;
    132. attacking=true;
    133. }
    134.  
    135. if(Input.GetKeyDown(KeyCode.Space))
    136. {
    137. jump=true;
    138. }
    139. }
    140.  
    141. privatevoidFlip(floathorizontal)
    142. {
    143. if(horizontal>0&& !facingRight || horizontal<0&&facingRight)
    144. {
    145. facingRight= !facingRight;
    146.  
    147. Vector3theScale=transform.localScale;
    148.  
    149. theScale.x*=-1;
    150.  
    151. transform.localScale=theScale;
    152. }
    153. }
    154.  
    155. privatevoidResetValues()
    156. {
    157. attack=false;
    158. jump=false;
    159. attacking=false;
    160. }
    161.  
    162. privateboolIsGrounded()
    163. {
    164. if(rb2d.velocity.y<=0)
    165. {
    166. foreach(Transform point ingroundPoints)
    167. {
    168. Collider2D[]colliders=Physics2D.OverlapCircleAll(point.position,groundRadius,whatIsGround);
    169.  
    170. for(inti=0;i<colliders.Length;i++)
    171. {
    172. if(colliders[i].gameObject !=gameObject)
    173. {
    174. returntrue;
    175. }
    176. }
    177. }
    178. }
    179. returnfalse;
    180. }
    181.  
    182. voidOnCollisionEnter2D(Collision2Dcol)
    183. {
    184. if(col.gameObject.CompareTag("Enemy"))
    185. {
    186. if(attackTimer==0&&attack==true)
    187. {
    188. attackTimer=cooldown;
    189. Health-=5f;
    190. infoText.text="Health:"+Health;
    191. }
    192. }
    193.  
    194. }
    195. }
    196.  
     
  11. JaimieVos

    JaimieVos

    Joined:
    Jun 21, 2015
    Posts:
    193
    Thx i fixed it with debug.log. 1 if statement was wrong.
    The only thing now is that the player can't die.
     
  12. JaimieVos

    JaimieVos

    Joined:
    Jun 21, 2015
    Posts:
    193
    Fixed :D!