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 *== null)*
{
target = t;
break;
}
else if (targDist <= targetRad)
{
}
else if (targDist <= targetRad && target != t)
{
continue;
}
else if (targDist <= targetRad && target == t)
{
break;
}
else if (targDist > targetRad && target == t)
{
target = null;
break;
}
}
}
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, targetRad);
}
}