+1 vote

Does anyone know how to use the pop_front in c#

in Engine by (38 points)

1 Answer

+1 vote

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.

by (1,100 points)

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();

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.

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.