//My turrets were shooting their targets just fine until I added the SetTarget(); method. I’m not sure what could be going on. Also let me know if there is a better way to upload code to a topic.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Turret : MonoBehaviour
{
public Transform Target;
public Transform RotatingObject;
[SerializeField] private float attackRange = 10;
[SerializeField] private ParticleSystem bulletParticles;
void Start()
{
}
// Update is called once per frame
void Update()
{
SetTarget();
if (Target)
{
RotatingObject.LookAt(Target);
ShootEnemy();
}
else
{
Shoot(false);
}
}
private void SetTarget()
{
var sceneEnemies = FindObjectsOfType<DamageToEnemy>();
if(sceneEnemies.Length == 0) { return; }
Transform closestEmemy = sceneEnemies[0].transform;
foreach(DamageToEnemy testEnemy in sceneEnemies)
{
closestEmemy = GetCloesest(closestEmemy, testEnemy.transform);
}
Target = closestEmemy;
}
private Transform GetCloesest(Transform transformA, Transform transformB)
{
var aDistance = Vector3.Distance(transform.position, transformA.position);
var bDistance = Vector3.Distance(transform.position, transformB.position);
if(aDistance < bDistance)
{
return transformA;
}
return transformB;
}
private void ShootEnemy()
{
float distanceToEnemy = Vector3.Distance(Target.transform.position, gameObject.transform.position);
if (distanceToEnemy < attackRange)
{
Shoot(true);
}
else
{
Shoot(false);
}
}
private void Shoot(bool isActive)
{
var emit = bulletParticles.emission;
emit.enabled = isActive;
}
}