Hey guy’s
I’m kinda new on unity scripting and need some help, I made a enemy health script, but now i cant seem to figure out how to make it lose health when I shoot at it.
This is my Enemy Health script
using UnityEngine;
using System.Collections;
public class EnemyHealth : MonoBehaviour {
public int maxHealth = 100;
public int curHealth = 100;
public float healthBarLength;
// Use this for initialization
void Start () {
healthBarLength = Screen.width / 2;
}
// Update is called once per frame
void Update () {
AddjustCurrenthealth(0);
}
void OnGUI() {
GUI.Box(new Rect(10, 40, healthBarLength, 20), curHealth + "/" + maxHealth);
}
public void AddjustCurrenthealth(int adj) {
curHealth += adj;
if(curHealth < 0)
curHealth = 0;
if( curHealth > maxHealth)
curHealth = maxHealth;
if(maxHealth < 1)
maxHealth = 1;
healthBarLength = (Screen.width /2) * (curHealth / (float)maxHealth);
}
}
Do you have that in C sharp? because my health bar is in C sharp
from top to buttom of his script: (Note: This is completely untested :P)
using UnityEngine;
using System.Collections;
public class TEST : MonoBehaviour {
GameObject Bullet;
bool activeUnit = false;
void Update()
{
if(activeUnit)
{
if(Input.GetButtonDown("Fire2")){
GameObject bullet = Instantiate(Bullet, GameObject.Find("SpawnPoint").transform.position,
Quaternion.identity);
bullet.rigidbody.AddForce(transform.forward * 5000);
bullet.active = true;
}
}
}
}
And for the bullet:
using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour {
float damage = 5.0f;
private Vector3 lastPosition;
void OnEnable() {
lastPosition = transform.position;
}
void LateUpdate()
{
RaycastHit hit;
Ray r = new Ray(lastPosition, transform.position-lastPosition);
float distance = Vector3.Distance(transform.position, lastPosition);
if(Physics.Raycast(r,hit,distance))
{
hit.collider.gameObject.SendMessage("TakeDamage", damage,
SendMessageOptions.DontRequireReceiver);
Destroy(gameObject);
}
lastPosition = transform.position;
}
}
And for the object that has the healthbar etc …
float hitPoints = 100.0f;
void TakeDamage(float amount)
{
hitPoints -= amount;
if(hitPoints <= 0.0f) {
Destroy(gameObject);
}
}
thanks, I’l give it a trye