- Home /
GameObject array problems c#
I'm having issues with arrays, Im trying to sort and remove elements from an array if they are too far away, But what ever method I try it does not work. I'm trying a for loop at the moment, but it only loops once, even though the debug shows it has a length of 3.
targets = GameObject.FindGameObjectsWithTag("Targets");
Debug.Log("l = "+targets.Length);
for(int i = 0; i <= targets.Length; i++){
//if(Vector3.Distance(heli.position,targets[i].transform.position) < targetRange){
Debug.Log ("item "+i);
tempTarg[i] = targets[i];
//}
}
targets = tempTarg;
target = targets[Random.Range(0, targets.Length)].transform;
Anyone have any idea about this.
Also there are references to an array.Remove function, But it does not appear for me, unless it doesn't exist for C#. also just seem to be having general issues with arrays, like .Length does not appear in the method list.
I notice one problem in your for loop: i <= targets.Length
will cause problems. Arrays are 0 indexed, which means that you get the elements of the array by calling array[i]
, where i is a value between 0 and array.Length*-1*, inclusive. By using
Also, you can't remove objects from an array - .NET arrays are of static length. This allows them to have extremely high performance, but means you can't resize them. I recommend using a List structure if you absolutely must resize the collection.
Also, the Array class is not the same thing as arrays. In C#, the Array class holds extra methods for use with arrays, while most general things like Length are just members of array instances.
You may want to research the different collection types.
Remove() is not part of the built-in array. There is a RemoveAt() in the .NET generic list, but that is not what FindGameObjectWithTag() returns.
One issue I see (which I don't think is at the root of the issue you describe) is that your for() loop executes one too many times. It uses '
for (int i = 0; i < targets.Length; i++) {
Your answer
![](https://koobas.hobune.stream/wayback/20220613120244im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to set to game objects's position from 2 different game objects arrays equal to each other? 0 Answers
Read different game objects into array at same time? 2 Answers
How to select an Game Object from an Item List 0 Answers
How can i get ONLY the childrens of a GameOnbject with GetComponentsInChildren method? 5 Answers
NullReferenceException error in an array of objects 0 Answers