- Home /
Emptying and filling Arrays on command? C#
Hi All,
I'm looking to solve a problem, and my understanding of arrays is not good enough to do so, here's what I'm after:
An array which fills up with X number of GameObjects, any of which could be destroyed at any time. Under certain circumstances (let's say, a button is pressed), I'd like to be able to fill up the empty spaces of the array with more GameObjects.
I don't think it's important but the objects will be randomly placed and will all be identical.
Is there some kind of array or combo of array & loop that can achieve this? I would imagine there is some way of filling all the empty positions in an array.
Thanks!
P.S I'm working in C#
Answer by joelfivat · Jan 23, 2014 at 12:15 PM
Is that what you are looking for ?
GameObject[] array = new GameObject[x];
for(int i=0; i<array.Length; i++){
if(array[i]==null){
array[i] = your game object
}
}
You can find a great documentation about arrary in C# here : http://www.dotnetperls.com/array
Yes!! That looks like the basis that I need to solve it. Just to clarify, will an array position be automatically converted to 'null' if the object is destroyed? Or will I need to include code to do that.
Thanks!
Destroying the object won't set the array position to null.
Actually, since there is a reference in the array pointing to the gameObject, this will prevent the object from being destroyed. You won't see it in the scene anymore, but it will still be in memory, so yes, you need to set it to null manually :)
Your answer
Follow this Question
Related Questions
How to modify specific GameObjects in an array of GameObjects? 1 Answer
Make an array of all visible objects 1 Answer
2D array of GameObjects C# 2 Answers
How to put gameObjects to the list? 4 Answers
How do i change a sprite when another gameobject with the same prefab is colliding / is near 1 Answer