- Home /
Tower Defense turret with multiple targets within range. Help with targeting and nulling.
Please take a look at my code. I set my array to a Length of 5, and I intentionally have only 3 gameobjects: a Cube, Sphere, and Capsule, each with the Shape class (inherited, but it doesnt matter). My problem with the script is, whenever a first Shape is added to the target list, and then a second one is added, then the first one is nulled due to out of range, the second Shape will occupy the null element above it.
Im sure itis about the for loop, but I am unsure of how to prevent a Shape from entering the target array more than once. Here is the code:
public class TarGetter : MonoBehaviour
{
private const string TARGETING_GETTER = "Target Getter";
[SerializeField] float targetRad;
int targetAllowed = 5;
[SerializeField] Shape[] target;
private void Awake()
{
gameObject.name = TARGETING_GETTER;
}
void Start()
{
target = new Shape[targetAllowed];
//InvokeRepeating("UpdateTargets", 0f, 0.5f);
}
private void Update()
{
UpdateTargets();
}
void UpdateTargets()
{
Shape[] targetables = FindObjectsOfType<Shape>();
foreach(Shape t in targetables)
{
float targDist = Vector3.Distance(transform.position, t.transform.position);
for (int i = 0; i < target.Length; i++)
{
if (targDist <= targetRad && target[i] == null)
{
target[i] = t;
break;
}
else if (targDist <= targetRad)
{
}
else if (targDist <= targetRad && target[i] != t)
{
continue;
}
else if (targDist <= targetRad && target[i] == t)
{
break;
}
else if (targDist > targetRad && target[i] == t)
{
target[i] = null;
break;
}
}
}
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, targetRad);
}
}
Answer by Nightylion · Jan 20, 2020 at 12:22 PM
Shapes actually shouldn't be able to enter in list twice, since you use foreach(). Every shape will do only 1 iteration.
I am not sure where the problem is, but try change your for() loop to something like that:
for (int i = 0; i < target.Length; i++)
if (target[i] == null) //add this
{
if (targDist <= targetRad && target[i] == null)
{
target[i] = t;
//break;
}
else if (targDist <= targetRad)
{
}
else if (targDist <= targetRad && target[i] != t)
{
continue;
}
else if (targDist <= targetRad && target[i] == t)
{
//break;
}
else if (targDist > targetRad && target[i] == t)
{
target[i] = null;
//break;
}
break; //add this
}
With this every shape will operate with just first nulled position in your array.