could someone please tell me why after clearing array and checking it again, i'm not getting length == 0?
public class test : MonoBehaviour
{
public GameObject[] allWayPoints;
public GameObject wayPoint;
void Start()
{
for(int i = 0; i < 10; i )
{
GameObject pathPrefab = Instantiate(wayPoint, new Vector3(0, 0, 0), Quaternion.identity);
pathPrefab.tag = "PathPoint";
}
allWayPoints = GameObject.FindGameObjectsWithTag("PathPoint");
Debug.Log(allWayPoints.Length);
allWayPoints = GameObject.FindGameObjectsWithTag("PathPoint");
foreach (GameObject go in allWayPoints)
{
Destroy(go);
}
allWayPoints = new GameObject[0];
Debug.Log(allWayPoints.Length);
allWayPoints = GameObject.FindGameObjectsWithTag("PathPoint");
Debug.Log(allWayPoints.Length);
}
}
CodePudding user response:
The only time length of the array will be 0 is when you explicitly set it to 0, as you can see in your logs.
When you destroy a GameObject, it isn't immediately removed either, and destroying a GameObject doesn't make the array smaller. Since the GameObject isn't immediately removed, you still find the old "to be removed" references from the scene.
An array is a collection with a fixed number of values/indexes, and it's length will always be as long as it was on creation as it occupies a specific piece of memory regardless of its actual content.
See fiddle here, array with only nulls still has the same length as it had upon creation, even though it's effectively empty. https://dotnetfiddle.net/VmigUO
