Search Unity

[help] enemy Health Bar decrease at the same time

Discussion in 'Scripting' started by Apriyanto, Apr 8, 2013.

  1. Apriyanto

    Apriyanto

    Joined:
    Jul 29, 2012
    Posts:
    17
    Hi all~ i have problems on my enemy health bar, when i try to hit single enemy the health bar on all enemies will decrease at the same time, i don't know what happen in here. Can someone help me Fix this ?

    $ScreenShot2013-04-09at25327AM_zps703a0695.png

    here is my scripts Player attack :

    Code (csharp):
    1. var targets : GameObject [];
    2.     var attackTimer : float;
    3.     var coolDown : float;
    4.     var prefabBullet : Transform;
    5.     var shootForce : float;
    6.     var hand : Transform;
    7.     var fireRate : float = 1.4f;
    8.    
    9.     public var playerTarget : Transform;
    10.     public var HealthEnabled:boolean = false;
    11.  
    12.     public var lastPlayerTarget;
    13.    
    14.     private var nextFire : float = 0f;
    15.    
    16.    
    17.     // Use this for initialization
    18.     function Start () {
    19.    
    20.         targets = GameObject.FindGameObjectsWithTag("Enemy");
    21.         attackTimer = 0;
    22.         coolDown = 1.0f;
    23.    
    24.     }
    25.    
    26.     // Update is called once per frame
    27.     function Update ()
    28.     {
    29.    
    30.        
    31.         if(Health == 0)
    32.         {
    33.        
    34.         PlayerAnimation.Stop("dead");
    35.         }
    36.  
    37.         if(attackTimer > 0)
    38.             attackTimer -= Time.deltaTime;
    39.         if(attackTimer < 0)
    40.             attackTimer = 0;
    41.         if(Input.GetKeyUp(KeyCode.Mouse0) || Input.GetKey (KeyCode.Return)  prefabBullet.rigidbody)
    42.         {
    43.            
    44.             if(attackTimer == 0)
    45.             {
    46.                 if( Health.health > 0  EnemyHealthJava2.healthBarLength > 0)
    47.                 {
    48.                 //Health.health > 5;
    49.                 Attack();
    50.                 attackTimer = coolDown;
    51.                 }
    52.                
    53.             }
    54.         }
    55.    
    56.     }
    57.    
    58.     function Attack()
    59.     {
    60.        
    61.            for (var i = 0; i < targets.Length; i++)
    62.         {
    63.        
    64.        
    65.            
    66.          var distance : float = Vector3.Distance(targets[i].transform.position, transform.position);
    67.  
    68.          var dir : Vector3 = (targets[i].transform.position - transform.position).normalized;
    69.  
    70.          var direction : float = Vector3.Dot(dir, transform.forward);
    71.  
    72.        
    73.         if(distance < 10)
    74.         {
    75.             if(direction > 0)
    76.             {
    77.                
    78.                 nextFire = Time.time + fireRate;
    79.                 var clone : Transform = Instantiate(prefabBullet, hand.position, hand.rotation) as Transform;
    80.                 clone.rigidbody.velocity = transform.TransformDirection(Vector3.forward * 20);
    81.                
    82.                 animation.Play("shoot");
    83.                 var eh : EnemyHealthJava2 = targets[i].GetComponent("EnemyHealthJava2");
    84.                 eh.AdjustCurrentHealth(-10);
    85.            
    86.             }
    87.         }
    88.    
    89.         }  
    90.     }
    ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    here is the enemy health:

    Code (csharp):
    1. var playerName : String;
    2. var adjustment : float= 2.3f;
    3. var healthTex : Texture2D;
    4.  
    5.  
    6.  
    7. static var health : int = 100;
    8. static var curHealth : int = 100;
    9. static var enemy : String;
    10. static var alive : boolean = true;
    11. static var healthBarLength : float = 100;
    12.  
    13.  
    14. private var worldPosition : Vector3= new Vector3();
    15. private var screenPosition : Vector3= new Vector3();
    16. private var myTransform : Transform;
    17. private var myCamera : Camera;
    18. private var healthBarHeight : int= 5;
    19. private var healthBarLeft : int= 110;
    20. private var barTop : int= 1;
    21. //private var healthBarLength : float= 100;
    22. private var labelTop : int= 18;
    23. private var labelWidth : int= 110;
    24. private var labelHeight : int= 15;
    25.  
    26. private var myStyle : GUIStyle= new GUIStyle();
    27.  
    28.  
    29.  
    30. function Awake ()
    31. {
    32.     myTransform = transform;
    33.     myCamera = Camera.main;
    34.     myStyle.normal.textColor = Color.green;
    35.     myStyle.fontSize = 12;
    36.     myStyle.fontStyle = FontStyle.Bold;
    37.     myStyle.clipping = TextClipping.Overflow;
    38. }
    39. function Update () {
    40.  
    41.     if (healthBarLength != null  curHealth <= 0)
    42.         {
    43.            
    44.            
    45.             Destroy(gameObject);
    46.             Debug.Log("Enemy Death");
    47.             return;
    48.         }
    49.  
    50. }
    51.  
    52. function OnGUI ()
    53. {
    54.  
    55.     worldPosition = new Vector3(myTransform.position.x, myTransform.position.y + adjustment,myTransform.position.z);
    56.     screenPosition = myCamera.WorldToScreenPoint(worldPosition);
    57.  
    58.     GUI.Box(new Rect(screenPosition.x - healthBarLeft / 2, Screen.height - screenPosition.y - barTop,100, healthBarHeight), "");
    59.     GUI.DrawTexture(new Rect(screenPosition.x - healthBarLeft / 2, Screen.height - screenPosition.y - barTop,healthBarLength, healthBarHeight), healthTex);
    60.     GUI.Label(new Rect(screenPosition.x - labelWidth / 2, Screen.height - screenPosition.y - labelTop, labelWidth, labelHeight), playerName, myStyle);
    61. }  
    62.  
    63.  
    64. static function  UpOrDown (amount : int)
    65. {
    66.  
    67.     healthBarLength += amount;
    68. }
    69.  
    70.  
    71. public function AdjustCurrentHealth( adj : int)
    72. {
    73.  
    74.     healthBarLength += adj;
    75.  
    76.     if(healthBarLength <=0  alive)
    77.     {
    78.         alive = false;
    79.         healthBarLength = 0;
    80.    
    81. }
    82.     if(healthBarLength > health)
    83.     healthBarLength = health;
    84.  
    85.     if(health < 1)
    86.     health = 1;
    87. }
    Please Help me to Fix this
     
    Last edited: Apr 9, 2013
  2. BFGames

    BFGames

    Joined:
    Oct 2, 2012
    Posts:
    1,543
    Your loop seems ok. What happens if you change distance < 2 or something like that?
     
  3. oneXwork

    oneXwork

    Joined:
    Mar 3, 2011
    Posts:
    266
    Remove the static in the currenthp in enemy,static mean thtoughout the game there is only one currenthp mean all enemy got the same value of HP.
     
  4. meganaut

    meganaut

    Joined:
    Mar 8, 2012
    Posts:
    18
    So.. you are getting a list of all enemys (game objects with the tag "enemy") and then when you are performing an attack, you are iterating through all of those enemy game objects that are closer than 10 units, getting the health bar and reducing its value by 10... so its not a bug in the healthbar. its a bug in your attack function. I think you have probably been coding too many hours with not enough sleep :)

    You need to specify which exact enemy you are attacking not just attack all within a range :)

    You should probably use tracing infront of your player.. or possibly find enemys within like 0-2 units where the dot product of your units forward vector and the vector from your player to the enemy is positive (i.e. less than 90 deg from directly infront.)

    edit: yeah like wx said.. static health var is a problem
     
    Last edited: Apr 8, 2013
  5. Apriyanto

    Apriyanto

    Joined:
    Jul 29, 2012
    Posts:
    17
    i fixed this scripts and i changed the var static healthBarLength, the players can Attack one by one without enemy healthbar decrease together.

    here my fixed scripts :


    Player Attack :
    Code (csharp):
    1.  
    2.     var targets : GameObject [];
    3.     var attackTimer : float;
    4.     var coolDown : float;
    5.     var prefabBullet : Transform;
    6.     var shootForce : float;
    7.     var hand : Transform;
    8.     var fireRate : float = 1.4f;
    9.     var damage : int = 10;
    10.    
    11.     public var playerTarget : Transform;
    12.     public var HealthEnabled:boolean = false;
    13.  
    14.     public var lastPlayerTarget;
    15.    
    16.     private var nextFire : float = 0f;
    17.    
    18.    
    19.     // Use this for initialization
    20.     function Start () {
    21.        
    22.         targets = GameObject.FindGameObjectsWithTag("Enemy");
    23.        
    24.         attackTimer = 0;
    25.         coolDown = 1.0f;
    26.        
    27.    
    28.     }
    29.    
    30.     // Update is called once per frame
    31.     function Update ()
    32.     {
    33.    
    34.        
    35.        
    36.         if(Health == 0)
    37.         {
    38.        
    39.         PlayerAnimation.Stop("dead");
    40.         }
    41.  
    42.         if(attackTimer > 0)
    43.             attackTimer -= Time.deltaTime;
    44.         if(attackTimer < 0)
    45.             attackTimer = 0;
    46.         if(Input.GetKeyUp(KeyCode.Mouse0) || Input.GetKey (KeyCode.Return)  prefabBullet.rigidbody)
    47.         {
    48.            
    49.             if(attackTimer == 0)
    50.             {
    51.                 if( Health.health > 0 )
    52.                 {
    53.                 //Health.health > 5;
    54.                 Attack();
    55.                 attackTimer = coolDown;
    56.                 }
    57.                
    58.             }
    59.         }
    60.    
    61.     }
    62.    
    63.     function Attack()
    64.     {
    65.        
    66.            for (var i = 0; i < targets.Length; i++)
    67.         {
    68.        
    69.        
    70.            
    71.          var distance : float = Vector3.Distance(targets[i].transform.position, transform.position);
    72.  
    73.          var dir : Vector3 = (targets[i].transform.position - transform.position).normalized;
    74.  
    75.          var direction : float = Vector3.Dot(dir, transform.forward);
    76.  
    77.        
    78.         if(distance < 10  gameObject != null)
    79.         {
    80.             if(direction > 0  gameObject != null)
    81.             {
    82.                 gameObject !=null;
    83.                 nextFire = Time.time + fireRate;
    84.                 var clone : Transform = Instantiate(prefabBullet, hand.position, hand.rotation) as Transform;
    85.                 clone.rigidbody.velocity = transform.TransformDirection(Vector3.forward * 20);
    86.                
    87.                 animation.Play("shoot");
    88.                
    89.                
    90.                 targets[i].gameObject.GetComponent("EnemyHealthJava2").AdjustCurrentHealth(damage);
    91.                
    92.             }
    93.         }
    94.    
    95.         }  
    96.     }
    97.  
    and the Enemy Health

    Code (csharp):
    1. var playerName : String;
    2. var adjustment : float= 2.3f;
    3. var healthTex : Texture2D;
    4. var healthBarLength : int = 100;  // I changed this, not use static
    5.  
    6.  
    7. static var health : int = 100;
    8. static var curHealth : int = 100;
    9. static var enemy : String;
    10. static var alive : boolean = true;
    11.  
    12.  
    13.  
    14. private var worldPosition : Vector3= new Vector3();
    15. private var screenPosition : Vector3= new Vector3();
    16. private var myTransform : Transform;
    17. private var myCamera : Camera;
    18. private var healthBarHeight : int= 5;
    19. private var healthBarLeft : int= 110;
    20. private var barTop : int= 1;
    21. //private var healthBarLength : float= 100;
    22. private var labelTop : int= 18;
    23. private var labelWidth : int= 110;
    24. private var labelHeight : int= 15;
    25.  
    26. private var myStyle : GUIStyle= new GUIStyle();
    27.  
    28.  
    29.  
    30. function Awake ()
    31. {
    32.    
    33.     healthBarLength = 100;
    34.     alive = true;
    35.     myTransform = transform;
    36.     myCamera = Camera.main;
    37.     myStyle.normal.textColor = Color.green;
    38.     myStyle.fontSize = 12;
    39.     myStyle.fontStyle = FontStyle.Bold;
    40.     myStyle.clipping = TextClipping.Overflow;
    41. }
    42. function Update () {
    43.    
    44.     if (healthBarLength != null  curHealth <= 0)
    45.         {
    46.            
    47.            
    48.         animation [ "dead" ].wrapMode = WrapMode.Once;
    49.         animation.CrossFade("dead");
    50.        
    51.         }
    52.    
    53.        
    54.    
    55. }
    56.  
    57. function OnGUI ()
    58. {
    59.  
    60.     worldPosition = new Vector3(myTransform.position.x, myTransform.position.y + adjustment,myTransform.position.z);
    61.     screenPosition = myCamera.WorldToScreenPoint(worldPosition);
    62.  
    63.     GUI.Box(new Rect(screenPosition.x - healthBarLeft / 2, Screen.height - screenPosition.y - barTop,100, healthBarHeight), "");
    64.     GUI.DrawTexture(new Rect(screenPosition.x - healthBarLeft / 2, Screen.height - screenPosition.y - barTop,healthBarLength, healthBarHeight), healthTex);
    65.     GUI.Label(new Rect(screenPosition.x - labelWidth / 2, Screen.height - screenPosition.y - labelTop, labelWidth, labelHeight), playerName, myStyle);
    66. }  
    67.  
    68.  
    69. public function  UpOrDown (amount : int)
    70. {
    71.  
    72.     health += amount;
    73. }
    74.  
    75.  
    76. public function AdjustCurrentHealth( adj : int)
    77. {
    78.  
    79.     healthBarLength -= adj;
    80.  
    81.     if(gameObject != null  healthBarLength <=0 )
    82.     {
    83.        
    84.         alive = false;
    85.         healthBarLength = 0;
    86.         animation.Play("dead");
    87.         Destroy(gameObject);
    88.        
    89.    
    90.     }
    91.     if(gameObject != null  healthBarLength > health )
    92.     healthBarLength = health;
    93.  
    94.     if(health < 1)
    95.     health = 1;
    96.     return;
    97.    
    98. }
    99.    
    100.  
    But I have some problems in Here, when i killed one enemy and continue hit another enemy there have some message

    Code (csharp):
    1. MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
    2. Your script should either check if it is null or you should not destroy the object.
    3. PlayerAttack.Attack () (at Assets/Garudayana Projects/Scripts/PlayerAttack.js:70)
    4. PlayerAttack.Update () (at Assets/Garudayana Projects/Scripts/PlayerAttack.js:53)
    I don't know what happen in here , because i already make gameObject != null ;

    The first enemy i just killed already Destroy, but when i am try to hit another enemies the player still can attack and another 3D model enemies still appears, but the notification tell, the game object are destroy .


    help me pls
     
    Last edited: Apr 8, 2013
  6. meganaut

    meganaut

    Joined:
    Mar 8, 2012
    Posts:
    18
    How often do you update your targets array? if a gameobject is destroyed, is there still a reference to it in that array?

    You should make sure its not null before you calculate "var distance" .. line 70 in PlayerAttack
     
  7. Apriyanto

    Apriyanto

    Joined:
    Jul 29, 2012
    Posts:
    17
    Hi all~ thank you for participation .

    Now i already FIX the scripts for game object, now all working correctly ,


    Here is the scripts for Fix the Game object issue :

    Player attack : ( put new declaration in here)


    Code (csharp):
    1. function Attack()
    2. {
    3.     for (var i = 0; i < targets.Length; i++)
    4.     {
    5.         if (targets[i] == null) continue; // skip destroyed targets
    6.         var distance : float = Vector3.Distance(targets[i].transform.position, transform.position);
    7.         var dir : Vector3 = (targets[i].transform.position - transform.position).normalized;
    8.         ...
     
  8. BlackMantis

    BlackMantis

    Joined:
    Feb 7, 2010
    Posts:
    1,475
    Off Topic - Looked at your scripts to see how the GUI health bar follows the enemies around. I have never been able to script GUI to follow the enemy without some kind of problem. (eg) I notice that directly behind the player is a copy of the GUI bar and the bar scales big when close. Also moves up the Y axis. These are for the most part the same problems I'm having in my attempts. Are you having the same?
     
  9. Apriyanto

    Apriyanto

    Joined:
    Jul 29, 2012
    Posts:
    17
    No because i using GUIstyle to fix the scale, and now this scripts already done for me without error, and without enemy healthbar decrease together too
     
  10. BlackMantis

    BlackMantis

    Joined:
    Feb 7, 2010
    Posts:
    1,475
    :eek: :eek:

    How can GUI style be used for such a fix. Please Explain. What about the draw behind the camera issue. :cool: