Good day im having trouble indentifing where i redeclare the eh variable
what im trying too do is damage the enemy and the temporal workaround i found is to keep the declaration outside the if statement but i get a null exeption cause enemigo is not declared yet
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TorretaAI : MonoBehaviour {
public Transform BaseTorreta;
public Transform Enemigo;
public List<Transform> Enemigos = new List<Transform>();
public float RotationSpeed = 1;
public Rigidbody bulletPrefab;
public Transform bulletSpawn;
public float AttackSpeed;
public float shotInterval = 0.5f;
public float bulletSpeed = 500f;
public float counter;
public bool Timer = true;
public float tiempo;
public int Daño;
private VidaEnemigo eh;
// Use this for initialization
void Start () {
counter += Time.deltaTime;
}
void OnTriggerStay (Collider other){
if (other.tag == "enemigo") {
if (!Enemigos.Contains(other.transform)){
Enemigos.Add(other.transform);
}
}
}
// Update is called once per frame
void Update () {
Enemigos.Sort(delegate(Transform t1, Transform t2){return Vector3.Distance(t1.position, BaseTorreta.position).CompareTo(Vector3.Distance(t2.position, BaseTorreta.position));});
if (Enemigos.Count > 0){
Enemigo = Enemigos [0];
}
if (Enemigo){
VidaEnemigo eh = (VidaEnemigo)Enemigo.gameObject.GetComponent ("VidaEnemigo");
BaseTorreta.rotation = Quaternion.Slerp( BaseTorreta.rotation, Quaternion.LookRotation( Enemigo.transform.position - BaseTorreta.position ), Time.deltaTime * RotationSpeed );
if (Time.time >= AttackSpeed)
{
Rigidbody bullet = Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation) as Rigidbody;
bullet.rigidbody.AddForce(transform.forward * bulletSpeed);
AttackSpeed = Time.time + shotInterval;
if (counter >= tiempo){
eh.AddjustCurrentHealth(-Daño);
counter = 0;
}
}
}
if (eh.curHealth <= 0){
Enemigo = null;
Enemigos.RemoveAt(0);
}
}
void OnTriggerExit (Collider other){
if (other.tag == "enemigo") {
if (Enemigos.Contains(other.transform)){
Enemigos.Remove(other.transform);
}
}
}
}
Since you have already declared your variable as private VidaEnemigo eh; you don't need to re-declare it in your if (Enemigo) code block since all methods from your script already have an access to it. Under if(Enemigo) just use it as: eh = (VidaEnemigo)Enemigo.gameObject.GetComponent ("VidaEnemigo");
– HarshadKLines 16 and 47, btw
– tanoshimi