Creating a Circular Buffer in Unreal Engine C++

Feb, 9 2021— #basic

A ring buffer or circular buffer is a fixed-size queue that updates its old values with new ones in order from the last to the first element each iteration.

This can be useful if there is an array of certain number of objects, which during the game should be replaced by new ones, shifting the entire array to the old elements, removing the oldest element and changing the first element with a new value.

Today we will look at the example of an array of float variables (TArray<float>).

The algorithm can also be implemented on the basis of "TCircularBuffer", but I prefer to do it on the basis of TArray, because it is more convenient to access the data directly if required.

The algorithm for changing data in the form of a circular buffer is actually very simple, and here is an example of a function that would shift all elements of CircularBufferArr array towards the old elements, and the first element is replaced by the "ValueToSet" variable:

void UCircularBuffer::ShiftElementsDown(float ValueToSet)
	for (int32 Index = CircularBufferArr.Num() - 1; Index > 0; Index--)
		CircularBufferArr[Index] = CircularBufferArr[Index - 1];
	CircularBufferArr[0] = ValueToSet;

And that is, in general, everything. It is very easy to implement.

By Georgy Treshchev

Unreal Engine Developer. Contact for any questions.