FString vs FName vs Text in Unreal
Unreal Engine, developed by Epic Games, is a popular game engine that powers many successful video games and interactive experiences. When working with Unreal Engine, you often encounter various data types for handling text and strings, including FString, FName, and Text. In this blog post, we’ll dive into these three text-related data types, explore their differences, and provide examples of when to use each one.
This post was originally posted at https://agrawalsuneet.github.io/blogs/fstring-vs-fname-vs-text-in-unreal/ and later reposted on Medium.
FString
FString, short for Fixed String
, is a dynamic string type used in Unreal Engine. It is similar to the standard C++ string (std::string) and is the most flexible option for handling text. Here are some key features and examples of FString usage:
Dynamic and mutable: You can change the contents of an FString after its creation.
FString MyString = "Hello, ";
MyString += "Unreal Engine!";
Ideal for text manipulation and formatting: FString is excellent for concatenation, manipulation, and formatting of text during runtime.
FString PlayerName = "John";
FString Greeting = FString::Printf(TEXT("Hello, %s!"), *PlayerName);
Performance considerations: FString has a small performance overhead compared to FName and Text due to its dynamic nature. Avoid excessive use in performance-critical code.
FName
FName, short for Fixed Name
, is a more specialized data type in Unreal Engine. It is primarily used to store and reference names, such as object names, property names, and asset names. Here’s why you might want to use FName:
Efficient memory usage: FName uses a global name table, which reduces memory overhead when storing the same name multiple times.
FName Firstname = FName(TEXT("John"));
FName SecondName = FName(TEXT("John"));
In this example, Firstname and SecondName both reference the same entry in the global name table, saving memory.
Ideal for identifying assets: When referencing assets like textures or materials, FName can be more efficient than FString or Text.
UTexture2D* MyTexture = LoadObject<UTexture2D>(nullptr, TEXT("TextureName"));
Not suitable for dynamic text: FName is immutable and not designed for dynamic text manipulation. Use FString or Text for such purposes.