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 /
avatar image
0
Question by JoshMBeyer · Dec 17, 2012 at 06:04 PM · multipledamagehowenemiesapply

Trouble with apply damage to enemy

I have a script attached to my projectile, and a script attached to all the enemies.

The script attached to my projectile, if the projectile hits a transform with a tag "Enemy", then apply damage by accessing the healthscript of the enemy. But lets say I have 4 of the prefab enemy in a line.. I shoot the first one repeatedly, (the 4th one dies, then the 3rd, then the 2nd, and finally the 1rst one dies) How do I get it to where each one has it's own health? Here is the two scripts I have so far.

 using UnityEngine;
 using System.Collections;
 
 /// <summary>
 /// 
 /// This is the 7.5mm bullet script.
 /// 
 /// This script is attached to the 7.5mmBullet.
 /// 
 /// </summary>
 
 public class RifleBullet : MonoBehaviour {
     
     //----------Variables Start-------------
     
     //A quick reference.
     private Transform myTransform;
     
     //The projectiles flight speed.
     private float projectileSpeed = 10;
     
     //Prevent the projectile from causing
     //further harm once it has hit something.
     private bool expended = false;
     
     //A ray projected in front of the projectile
     //to see if it will hit a recognisable collider.
     private RaycastHit hit;
     
     //The range of that ray.
     private float range = 1.5f;
     
     //The life span of the projectile.
     private float expireTime = 5;
     
     
     //--------------Variables End------------------
     
     
     // Use this for initialization
     void Start () 
     {
         myTransform = transform;
         
         //As soon as the projectile is created start a countdown
         //to destroy it.
         StartCoroutine(DestroyMyselfAfterSomeTime());
     }
     
     // Update is called once per frame
     void Update () 
     {
         //Translate the projectile in the up direction (the pointed
         //end of the projectile).
         myTransform.Translate(Vector3.up * projectileSpeed * Time.deltaTime);
         
         
         //If the ray hits something then execute this code.
         if(Physics.Raycast(myTransform.position,myTransform.up, out hit, range) &&
            expended == false)
         {
             //If the collider has the tag of Floor then..
             
             if(hit.transform.tag == "Enemy")
             {
                 //If hit and enemy, destroy self.
                 Destroy(myTransform.gameObject);
                 
                 //Access the AnimalHealhBar Script to apply damage.
                 GameObject zombie = GameObject.Find("Zombie");
                 AnimalHealthbar aHealthScript = zombie.GetComponent<AnimalHealthbar>();
                 aHealthScript.wasHitByRifle = true;
             }
         }
     }
     
     
     IEnumerator DestroyMyselfAfterSomeTime()
     {
         //Wait for the timer to count up to the expireTime
         //and then destroy the projectile.
         yield return new WaitForSeconds(expireTime);
         
         Destroy(myTransform.gameObject);
     }
 }


And this is the Enemy's health script.

 using UnityEngine;
 using System.Collections;
 
 public class AnimalHealthbar : MonoBehaviour {
     
     //-------------Variables Start---------------
     
     
     //The health bar texture is attached to this in the inspector.
     public         Texture     healthTex;
     
     //Quick references.
     private     Camera         myCamera;
     private     Transform     myTransform;
     private     Transform     triggerTransform;
         
     //These are used in determining whether the healthbar should be drawn
     //and where on the screen.
     private     Vector3     worldPosition            = new Vector3();
     private     Vector3     screenPosition          = new Vector3();
     private     Vector3     cameraRelativePosition     = new Vector3();
     
     private     float        minimumZ                 = 1.5f;
     
     
     //These variables are used in defining the health bar.
     public         int         labelTop                 = 18;
     public         int         labelWidth                 = 110;
     public         int         labelHeight             = 15;
     public         int         barTop                     = 1;
     public         int         healthBarHeight            = 5;
     public         int         healthBarLeft             = 110;
     public         float         healthBarLength;
     public         float         adjustment                 = 1;
     
     //Value of health and HealthBar
     public         float         myHealth;
     public         float         maxHealth                 = 100;
 
     public         bool         iWasHit                    = false;
     
     private     GUIStyle     myStyle                 = new GUIStyle();
     
     public         bool         wasHitByRifle             = false;
     public         bool         wasHitByAK                 = false;
     
     
     //------------------Variables End------------------
     
     void Start ()
     {
         myHealth = 100;
         
         //Reference to our transform.
         myTransform = transform;
         //Reference to Camera's transform.
         myCamera = Camera.main;
         
         //FontSize
         myStyle.fontSize = 12;
         //FontSyle set to Bold.
         myStyle.fontStyle = FontStyle.Bold;
         
         //Allow the text to extend beyond the width of the label.
         myStyle.clipping = TextClipping.Overflow;
     }
     
     
     // Update is called once per frame
     void Update () 
     {    
         //Figure out how long the health bar should be and to avoid a mathematical error set
         //the health bar length to 1 if the the player's health falls below 1.
         
 
         if(myHealth >= 1)
         {
             healthBarLength = (myHealth / maxHealth) * 100;    
         }
         
         
         if(myHealth <= 0)
         {
             Destroy(myTransform.gameObject);
         }
         
         
         if(wasHitByRifle == true)
         {
             //Create the function to take away 55-90 health.
             myHealth -= (Random.Range(55,100));
             wasHitByRifle = false;
         }
         
         if(wasHitByAK == true)
         {
             //Create the function to take away 55-90 health.
             myHealth -= (Random.Range(4,8));
             wasHitByAK = false;
         }
     }
     
     void OnGUI ()
     {
         //Only display the player's name if they are in front of the camera and also the 
         //player should be in front of the camera by at least minimumZ.
         
         if(cameraRelativePosition.z > minimumZ)
         {
             //Set the world position to be just a bit above the player.
             worldPosition = new Vector3(myTransform.position.x, myTransform.position.y + adjustment,
                                         myTransform.position.z);
             
             //Convert the world position to a point on the screen.
             screenPosition = myCamera.WorldToScreenPoint(worldPosition);
             
             
             //Draw the health bar and the grey bar behind it.
             GUI.Box(new Rect(screenPosition.x - healthBarLeft / 2, 
                              Screen.height - screenPosition.y - barTop,
                              100, healthBarHeight), "");
 
             GUI.DrawTexture(new Rect(screenPosition.x - healthBarLeft / 2,
                                      Screen.height - screenPosition.y - barTop,
                                      healthBarLength, healthBarHeight), healthTex);        
 
         }
     }
 }
Comment
Add comment · Show 1
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 JoshMBeyer · Dec 17, 2012 at 04:39 PM 0
Share

Sorry about the variables, they were in order until I clicked "Ask your question".

2 Replies

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

Answer by BilboStabbins · Dec 17, 2012 at 06:41 PM

You know which enemy has been hit by the ray by using the information stored in the hit variable and the collider that was intersected. So from your code you could say:

     if(Physics.Raycast(transform.position, transform.up, out hit)
     {
         if(hit.transform.tag == "Enemy")
         {
             AnimalHealthbar aHealthScript = hit.collider.gameObject.GetComponent<aHealthScript>();
             if (aHealthScript == null)
                 Debug.Log("Cannot find aHealthScript");

             else
                 aHealthScript.AnimalHealthbar.wasHitByRifle = true;

         }     
     }




Give that a try, it should work. Good luck! :)

Comment
Add comment · Show 2 · 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 JoshMBeyer · Dec 18, 2012 at 03:58 AM 0
Share

I am getting two error's now,

Assets/GameAssets/Scripts/PlayerScripts/A$$anonymous$$uBullet.cs(82,102): error CS0246: The type or namespace name `aHealthScript' could not be found. Are you missing a using directive or an assembly reference?

Assets/GameAssets/Scripts/PlayerScripts/A$$anonymous$$uBullet.cs(87,31): error CS1061: Type `AnimalHealthbar' does not contain a definition for `AnimalHealthbar' and no extension method `AnimalHealthbar' of type `AnimalHealthbar' could be found (are you missing a using directive or an assembly reference?)

avatar image JoshMBeyer · Dec 21, 2012 at 02:21 PM 0
Share

never $$anonymous$$d, I got that to work.. Although when my projectile speed is 100+ it only hits 1 out of 4 shots in the exact same spot. so I have to keep a relatively low projectile speed.

But thats good enough. This took forever to fix something so simple lol you help me alot.

avatar image
0

Answer by MWW · Dec 20, 2012 at 02:52 AM

You can add this script to any game object and it will destroy the game object after health reaches 0

 var MaxHealth : int = 100;
 var CurrentHealth : int;
 function Start () {
  CurrentHealth = MaxHealth;
 }
 function ApplyDamage ( Damage : float) {
 CurrentHealth-=Damage;
 if (CurrentHealth < 0)
 Destroy(gameObject);
 }
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 JoshMBeyer · Dec 21, 2012 at 02:23 PM 0
Share

Already have that applied in the enemyHealth script.

if(myHealth <= 0) { Destroy(myTransform.gameObject); }

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

11 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

Related Questions

how do i kill multiple enemies? 0 Answers

Enemies always dies in sequence 2 Answers

Fire to the multiple Enemies For 5 to 6 times 0 Answers

How do I apply damage to the enemy ai using melee weapon OnControllerColliderhit 0 Answers

JS script for applying damage to player when within a certain proximity to the Enemy. 2 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