- Home /
Add to Array
Hello,
i would like to add the distance value of each object in (foreach) to an array. For example i would like to fill slot one first and if i add an object filling in the requirements i would like to add its distance in slot 2.
Any Ideas?
using UnityEngine; using BehaviorDesigner.Runtime; using System.Linq; using System.Collections; using System.Collections.Generic;
public class SwarmLeader : MonoBehaviour {
public float[] distance;
public GameObject[] Swarm;
public GameObject Player;
public float closest;
public int swarmlength;
void Awake()
{
}
public void Update()
{
Swarm = GameObject.FindGameObjectsWithTag("Enemy");
distance = new float[Swarm.Length + 2];
swarmlength = Swarm.Length - 1;
foreach (GameObject Climbing in Swarm)
{
if (Climbing.name == ("swarm"))
{
float dist = Vector3.Distance(Climbing.transform.position, Player.transform.position);
distance[0] = dist;
if (dist <= Mathf.Min(distance))
{
Debug.Log("ImLeader " + Climbing.name);
}
}
}
}
}
Answer by CodesCove · Aug 03, 2020 at 06:31 PM
I'm not sure I understood you need and usage of the distance values correctly but here's one way: Change the foreach-loop to for-loop and use indexing to to go trough the gameobjects and to store the distances like this (pseudo code)
for(int i = 0; i < Swarm.Length; i++)
{
distance[i] = Vector3.Distance(Swarm[i].transform.position, ....
....
}
that way you get the distance array with matching gameobject array. The Vector3.Distance always returns positive value so you can set set the distance[i] to negative value if the distance value does not meet the requirements of you game. That way you can later quickly check the validity of those distances.. (valid = real distance value, not valid = negative).
Hope this helps..
PS. I need to add also that the finding gameobjects in the scene in the Update() is very taxing.. I suggest you make the enemy gameobject array so that it is updated only when necessary (if enemy is created or destroyed).