pop_front in c#

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By godotuser123

Does anyone know how to use the pop_front in c#

:bust_in_silhouette: Reply From: aXu_AP

I haven’t used C# with Godot a lot, but it seems that the preferred way is to use C# arrays and System.Collections.Generic classes over Godot.Collections.Array<T>. That class contains bare minimum for interfacing with the engine and you should use something like List<T> (generally good and versatile) or Queue<T> (optimal for push_back,pop_front style usage) if you don’t need to have array exported or used by gdscript.

This is untested, but should work (on 3.x):

static public T PopFront<T>(ref Godot.Collections.Array<T> array)
{
    T firstElement = array[0];
    T[] newArray = new T[array.Count - 1];
    array.CopyTo(newArray, 1);
    array = new Godot.Collections.Array<T>(newArray);
    return firstElement;
}

It’s not very good solution if the array is big since it gets copied twice (unless there’s some optimisation wizardry behind the scenes). I don’t know if there’s differences with Godot 4.

You can make that to an extension in C# and make it reusable everywhere, save this to a new file GodotArrayExtensions.cs, you can add more extension methods inside the class:

public static class GodotArrayExtensions {
    static public T PopFront<T>(this Godot.Collections.Array<T> array)
    {
        T firstElement = array[0];
        T[] newArray = new T[array.Count - 1];
        array.CopyTo(newArray, 1);
        array = new Godot.Collections.Array<T>(newArray);
        return firstElement;
    }
}

example usage:

var firstElement = foobarArray.PopFront();

Jukepoks1 | 2022-12-21 19:57

Extension are cool, but in this case it won’t work, because you need to have the array by ref in order to replace it. In the extension version the new version of the array gets discarded.

aXu_AP | 2022-12-21 20:16

I tried it out and it didn’t actually work. the CopyTo() method says the newArray is too small to fit the array to.

I fixed it and remade it, array is not disregarded, it is at is, but you get the first element out of it and the array is shortened:

public static class GodotArrayExtensions {
    static public T PopFront<T>(this Godot.Collections.Array<T> array)
    {
        T firstElement = array[0];
        array.RemoveAt(0);
        
        return firstElement;
    }
}

EDIT: oh I see what you mean it being disregarded by not using ref.

Jukepoks1 | 2022-12-21 21:20