- Home /
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);
}
}
}
Sorry about the variables, they were in order until I clicked "Ask your question".
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! :)
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?)
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.
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);
}
Already have that applied in the enemyHealth script.
if(myHealth <= 0) { Destroy(myTransform.gameObject); }
Your answer
Follow this Question
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