📜  tarray ue4 c++(1)

📅  最后修改于: 2023-12-03 15:35:15.474000             🧑  作者: Mango

Tarray in UE4 C++

Introduction

TArrays are dynamic arrays in Unreal Engine 4 (UE4) that offer a flexible way to store and manipulate collections of values of the same type. They are commonly used to store game objects, UI elements, and other data structures that may need to be updated or modified at runtime.

In this article, we will discuss the syntax and usage of TArrays in UE4 C++.

Syntax

TArrays can be declared and initialized using the following syntax:

TArray<Type> Name;

where Type is the data type of the elements to be stored in the array and Name is the name of the array.

For example, to declare an array of integers with 10 elements, we write:

TArray<int32> MyIntArray(10);

This creates an array of 10 integers, initialized with default values of 0.

Adding and Removing Elements

Elements can be added to a TArray using one of two methods: Add or Emplace.

The Add method is used to add an element of the array's type to the end of the array:

TArray<FString> MyStringArray;
MyStringArray.Add("Hello");
MyStringArray.Add("World");

The Emplace method is used to construct an element in place using a constructor with arguments:

TArray<FVector> MyVectorArray;
MyVectorArray.Emplace(1.0f, 2.0f, 3.0f);
MyVectorArray.Emplace(4.0f, 5.0f, 6.0f);

Elements can be removed from a TArray using the Remove method.

TArray<FString> MyStringArray;
MyStringArray.Add("Hello");
MyStringArray.Add("World");

MyStringArray.Remove("Hello"); // removes "Hello" from the array
Accessing Elements

Elements can be accessed using the [] operator.

TArray<FString> MyStringArray;
MyStringArray.Add("Hello");
MyStringArray.Add("World");

FString FirstElement = MyStringArray[0]; // retrieves "Hello"
FString LastElement = MyStringArray[MyStringArray.Num() - 1]; // retrieves "World"

You can also use the Get method to retrieve an element at a specific index, with a default value if the index is out of range:

TArray<FString> MyStringArray;
MyStringArray.Add("Hello");
MyStringArray.Add("World");

FString ThirdElement = MyStringArray.Get(2, "Default Value"); // retrieves "Default Value" since there is no third element.
Iterating Over Elements

TArrays can be iterated over using a for loop or a range-based for loop:

TArray<FString> MyStringArray;
MyStringArray.Add("Hello");
MyStringArray.Add("World");

for (int32 i = 0; i < MyStringArray.Num(); i++)
{
    FString& Element = MyStringArray[i];
    // do something with Element
}

for (const FString& Element : MyStringArray)
{
    // do something with Element
}
Conclusion

TArrays provide a versatile way to store collections of elements in UE4 C++. In this article, we covered the syntax for declaring, initializing and manipulating TArrays, accessing and iterating over elements.

For more information, you can refer to the official UE4 documentation on TArray.