- Home /
Question by
BlackWingsCorp · Feb 20, 2014 at 09:29 AM ·
c#enemydamagehealth
Enemyhealth component problem
Hey guys I'm writing a script that creates an array of all enemies then draws a ray from the player character, when the ray hits one it becomes the targeted enemy. But once I kill that enemy all the others get killed as well. Here's my scripts:
using UnityEngine;
using System.Collections;
public class Attack : MonoBehaviour {
public RaycastHit hit;
public Vector3 directionRay;
public int range = 20000;
public GameObject player;
public GameObject projectile;
public GameObject[] targets;
public static GameObject target;
public float speed = 200.0f;
bool isFired = SelfDest.isFired;
bool isReloading;
public Texture2D crosshair;
public int zoom = 200;
public int normal = 60;
public float smooth = 40;
public int bulletnumb = 12;
public int magazine = 3;
public AudioClip shoot;
public AudioClip reload;
public bool hashit = SelfDest.hashit;
// Use this for initialization
void Start () {
player = GameObject.FindGameObjectWithTag("Player");
isReloading = false;
targets = GameObject.FindGameObjectsWithTag("Enemy");
}
// Update is called once per frame
void Update () {
directionRay = transform.TransformDirection(Vector3.forward);
Debug.DrawRay(transform.position, directionRay * range, Color.red);
if(Physics.Raycast(transform.position, directionRay, out hit, range)){
if(hit.collider.gameObject.tag == "Enemy" && hashit == true){
target = hit.collider.gameObject;
}
}
if(Input.GetButton("Fire1") && bulletnumb >= 1){
if(!isFired){
isFired = true;
GameObject bullet = Instantiate(projectile, transform.parent.position, transform.parent.rotation) as GameObject;
bullet.rigidbody.velocity = transform.forward * speed;
audio.PlayOneShot(shoot);
bulletnumb--;
Physics.IgnoreCollision(bullet.collider, player.collider);
EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
eh.AdjustHealth(-30);
Invoke("Shoot", 0.45f);
}
}
if(bulletnumb == 0){
Invoke("Reload1", 0.75f);
}
if(Input.GetButton("Fire2") && isReloading == false){
isReloading = true;
Invoke("Reload2", 0.75f);
}
}
void Shoot(){
isFired = false;
}
void Reload1(){
if(bulletnumb <= 0 && magazine >= 1){
bulletnumb = 12;
audio.PlayOneShot(reload);
magazine--;
}
}
void Reload2(){
if(magazine >= 1){
bulletnumb = 12;
audio.PlayOneShot(reload);
magazine--;
isReloading = false;
}
}
void OnGUI(){
GUI.Box(new Rect(Screen.width/2, Screen.height/2, 10, 10), crosshair);
GUI.Box(new Rect(10, 35, 40, 20), bulletnumb + "/" + magazine);
}
}
Any help will be immensely appreciated. Thanks in advance
Comment
Sorry for the late reply. I use target in order to get the enemyhealth component in the bullet script. I found the error I'll post it. Thanks anyways
Best Answer
Answer by BlackWingsCorp · Feb 22, 2014 at 05:55 PM
Apparently the error was from the enemyhealth script I put the health int variable static. Anyways I hope the above script helps anyone trying to make a basic attack system.