Home > front end >  Godot inventory array, how to fill the first element
Godot inventory array, how to fill the first element

Time:02-24

I am making an array inventory in Godot. I have six null elements. I first use int find(variant,int from 0) to find the first null index. And then I use insert(position,variant) to fill in that null index. But I found that it keeps finding the null next to it and ends up filling them all. So, the result is a completely filled array. How do I make it fill the first found only once? Such as after I pick one item, one slot gets fill at a time.

CodePudding user response:

The insert method, inserts the element. So the Array will have all the elements it had, plus the one you inserted (The Array will have one more element). This is why the documentation mentions that it becomes slow on larger arrays.

As a result, insert never gets rid of any null (or any other element) the Array had. Which is why you keep finding the same.

What you want is not to insert a new element, but to overwrite an existing one. You do that with index access:

my_array[index] = new_value

For example, it can be something like this:

var index_of_null := my_array.find(null)
if index_of_null == -1:
    # null was not found
    print("the array is full") #or whatever
else:
    my_array[index_of_null] = new_value

Here we search for null in my_array, and if we find it (if find didn't return -1), we replace that null with a new_value. You should be able to adapt that code to your needs.

  • Related