I’m getting one error which I can’t figure out how to fix, I’ll include the code below, I’m trying to make it so when I tap on the attack button, it will deal damage to the closest enemy within a certain range, I just can’t figure out the range part. Can someone help me with this?
using UnityEngine;
namespace Combat {
public class PlayerCombat : MonoBehaviour {
public Animator animator;
[SerializeField] Transform target;
[SerializeField] float weaponRange = 2f;
[SerializeField] float weaponDamage = 5f;
public object currentWeaponConfig;
void Start() {
animator = GetComponent<Animator>();
}
public void Update() {
bool isInRange = Vector3.Distance(transform.position, target.position) < weaponRange;
}
public void KnightHeroAttack() {
animator.SetTrigger("KnightHeroAttack");
}
//Animation Event
void OldHit() {
Health healthComponent = target.GetComponent<Health>();
healthComponent.TakeDamage(weaponDamage);
}
void Hit() {
var hits = Physics.SphereCastAll(transform.position, 2.0f, transform.forward); //Collect objects in front of player
Health nearestEnemy = null;
float distanceCheck = 10000;
foreach(var hit in hits) {
if(hit.transform == transform) continue; //ignore self
if(hit.distance > distanceCheck) continue;
Health potentialEnemy = hit.transform.GetComponent<Health>();
if(potentialEnemy) {
nearestEnemy=potentialEnemy;
distanceCheck=hit.distance;
}
}
if(distanceCheck < currentWeaponConfig.GetRange()) return; //this should actually also account for no enemy found
target = nearestEnemy.gameObject.transform;
OldHit();
}
}
}