- Home /
remove health from 1 gameobject at a time
Hello,
i have made a health script that reduces the health when the object gets hit by a raycast. The script works for 1 gameibject per scene, but i want to be able to use it for multiple gameobjects (targets, enemies etc).
These are the scripts i have:
The raycastgun:
using UnityEngine;
using System.Collections;
public class GunHit
{
public float damage;
public RaycastHit raycastHit;
}
public class RaycastGun : MonoBehaviour
{
public float fireDelay = 0.1f;
public float damage;
public string buttonName = "Fire1";
public LayerMask layerMask = -1;
private bool readyToFire = true;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if (Input.GetButtonDown (buttonName) && readyToFire)
{
RaycastHit hit;
if (Physics.Raycast (transform.position, transform.forward,out hit, Mathf.Infinity,layerMask))
{
//Health verlagen wanneer
Health.currentHealth = Health.currentHealth - damage;
Debug.Log (Health.currentHealth);
}
}
}
}
and the health:
using UnityEngine;
using System.Collections;
public class Health : MonoBehaviour {
public float maxHealth = 100.0f;
static public float currentHealth = 100.0f;
// Use this for initialization
void Start ()
{
currentHealth = maxHealth;
}
void Update ()
{
if (currentHealth <= 0)
{
gameObject.SetActive(false);
}
}
}
thanks,
Requim36, i tried to do this. so i removed the static from the health script but now i get a error in the raycastgun script:
Assets/Scripts/GunNew/RaycastGun.cs(35,63): error CS0120: An object reference is required to access non-static member Health.currentHealth' Assets/Scripts/GunNew/RaycastGun.cs(35,40): error CS0120: An object reference is required to access non-static member Health.currentHealth'
Assets/Scripts/GunNew/RaycastGun.cs(36,51): error CS0120: An object reference is required to access non-static member `Health.currentHealth'
Answer by Requiem36 · Aug 04, 2015 at 12:56 PM
You currentHealth variable is static, so there can be only one value ever of it. Remove the static keyword to be able to have a value per-instance.