📜  UENUM ue4 - C++ (1)

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

UENUM in UE4 C++

Introduction

UENUM is a C++ macro defined in the Unreal Engine 4 (UE4) game engine that allows developers to create a custom enumeration data type. It stands for "UE4 ENUM" and is used extensively in game development to define various types of in-game properties.

Syntax

The basic syntax for UENUM is:

UENUM()
enum EnumType
{
    EnumValue1,
    EnumValue2,
    ...
};

Here, UENUM() is the macro that marks the enumeration as a UE4 enumeration, EnumType is the name of the enumeration data type, and EnumValue1, EnumValue2, etc. are the individual enumeration values.

Example

Suppose we want to define an enumeration to represent different types of weapons in a game. We can define it using UENUM as follows:

UENUM()
enum class EWeaponType
{
    Pistol,
    AssaultRifle,
    SniperRifle,
    Shotgun,
    MachineGun
};

Here, we have defined an enumeration data type named EWeaponType with five possible values: Pistol, AssaultRifle, SniperRifle, Shotgun, and MachineGun. Note that we have used the class keyword to define the enumeration as a scoped enum, which means that its values are only accessible using the scope resolution operator (::).

Usage

Once we have defined our enumeration, we can use it in various places in our code. For example, we can define a property in a class that uses our enumeration as follows:

UCLASS()
class AMyCharacter : public ACharacter
{
    GENERATED_BODY()

    UPROPERTY(EditAnywhere, Category = "Weapon")
    EWeaponType DefaultWeaponType;
};

Here, we have defined a UMAKEPROPERTY macro that creates a property named DefaultWeaponType for our AMyCharacter class. The EditAnywhere and Category attributes define how the property should be displayed in the UE4 editor.

We can also use our enumeration in switch statements to handle different cases:

void AMyCharacter::Attack(EWeaponType WeaponType)
{
    switch(WeaponType)
    {
        case EWeaponType::Pistol:
            FirePistol();
            break;
        case EWeaponType::AssaultRifle:
            FireAssaultRifle();
            break;
        case EWeaponType::SniperRifle:
            FireSniperRifle();
            break;
        case EWeaponType::Shotgun:
            FireShotgun();
            break;
        case EWeaponType::MachineGun:
            FireMachineGun();
            break;
        default:
            // handle invalid weapon type
            break;
    }
}

Here, we have defined an Attack function that takes an EWeaponType parameter and uses a switch statement to call the appropriate weapon firing function based on the weapon type.

Conclusion

In conclusion, UENUM is a useful macro in UE4 that allows developers to define custom enumeration data types for use in their games. By using UENUM and carefully defining our enumerations, we can make our code more readable and maintainable.