Hello guys, i want my script to deal damage to the closest enemy if hes in range. It should fire automatically without pushing any buttons. But the script makes 10 or 20 damage each time instead of 0.05 and the fire rate seems randomly. I tried hours with different ways but i cant figure out how to deal constantly damage to my enemys Maybe someone of you have an idea or can see where the problem is ?
using UnityEngine;
using System.Collections;
public class FK_Laser : MonoBehaviour {
public float Damage = 0.05f;
private float nextFire = 0.0f;
public float fireRate = 0.1f;
public float dist;
public float minshootdist = 4f;
public LayerMask WhatToHit;
Transform fireLine;
public Transform FireLinePrefab;
public GameObject closest = null;
public GameObject bullet;
// Use this for initialization
void Awake ()
{
fireLine = transform.FindChild("FireLine");
}
void Start()
{
InvokeRepeating("FindClosestEnemy", 1, 1f);
}
void Update()
{
dist = Vector2.Distance(transform.position, closest.transform.position);
Fire();
}
void Fire()
{
if (dist <= minshootdist && Time.time > nextFire)
{
Shoot();
nextFire = Time.time + fireRate;
}
}
public GameObject FindClosestEnemy()
{
GameObject[] Enemys;
Enemys = GameObject.FindGameObjectsWithTag("Zombie");
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject Enemy in Enemys)
{
Vector3 diff = Enemy.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closest = Enemy;
distance = curDistance;
}
}
return closest;
}
void Shoot()
{
Vector3 FireLinePosition = new Vector3(fireLine.position.x, fireLine.position.y);
RaycastHit2D hit = Physics2D.Raycast(FireLinePosition, closest.transform.position - FireLinePosition, 100, WhatToHit);
// Debug.DrawLine(FireLinePosition, closest.transform.position, Color.cyan);
if (hit.collider != null)
{
{
Debug.DrawLine(FireLinePosition, hit.point, Color.red);
if (hit.collider.GetComponent<HealthScriptZ1>())
{
HealthScriptZ1 Z1_HP = hit.collider.GetComponent<HealthScriptZ1>();
Z1_HP.HP -= Damage;
}
if (hit.collider.GetComponent<HealthScriptZ2>())
{
HealthScriptZ2 Z2_HP = hit.collider.GetComponent<HealthScriptZ2>();
Z2_HP.HP -= Damage;
}
if (hit.collider.GetComponent<HealthScriptZ3>())
{
HealthScriptZ3 Z3_HP = hit.collider.GetComponent<HealthScriptZ3>();
Z3_HP.HP -= Damage;
}
}
}
}
}