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. Dismiss Notice

[SOLVED]C#: When hit by collision player only taking damage once.

Discussion in 'Scripting' started by DarkBladeNemo, Dec 3, 2016.

  1. DarkBladeNemo

    DarkBladeNemo

    Joined:
    Aug 23, 2013
    Posts:
    116
    Hello everyone,

    ok so after messing with my game for awhile I decided to redo the way my player receives damage. The only problem now is that when the enemies hit my player he only gets damaged once and not continuously. If possible can someone help me to make it so that when my player is hit he takes damage continuously?

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class PlayerHealth : MonoBehaviour {
    7.  
    8.     public int health;
    9.     public Slider healthbar;
    10.     public EnemyDamageHandler enemy;
    11.  
    12.     void Start(){
    13.     }
    14.  
    15.     void Update(){
    16.         healthbar.value = health;
    17.     }
    18.  
    19.     void OnTriggerEnter2D(){
    20.        
    21.             health -= enemy.zombieDamage;
    22.  
    23.             Debug.Log ("Player Hit!");
    24.        
    25.            
    26.        
    27.  
    28.  
    29.  
    30.  
    31.         if(health <= 0){
    32.             Die();
    33.         }
    34.     }
    35.  
    36.     void Die(){
    37.         Destroy(gameObject);
    38.     }
    39. }
    40.  
    Thanks in advance
     
  2. romatallinn

    romatallinn

    Joined:
    Dec 26, 2015
    Posts:
    161
    Just change void OnTriggerEnter2D to void OnTriggerStay2D.
     
  3. DarkBladeNemo

    DarkBladeNemo

    Joined:
    Aug 23, 2013
    Posts:
    116
    Awesome that works but also causes insta death :/ Is there a wait to delay the script for a few seconds before taking damage again? I know I cant use Time.deltatime because its an Int.
     
  4. romatallinn

    romatallinn

    Joined:
    Dec 26, 2015
    Posts:
    161
    Simple timer....
    Code (CSharp):
    1.     float curTime = 0;
    2.     float nextDamage = 1;
    3.  
    4.  
    5.     void OnTriggerStay2D()
    6.     {
    7.         if (curTime <= 0) {
    8.             Debug.Log ("Damage");
    9.  
    10.             curTime = nextDamage;
    11.         } else {
    12.      
    13.             curTime -= Time.deltaTime;
    14.         }
    15.     }
     
  5. DarkBladeNemo

    DarkBladeNemo

    Joined:
    Aug 23, 2013
    Posts:
    116
    Great that worked like a charm. Will keep that in mind next time thank you.