Passing arguments to constructors in UE4?

Hey, here’s one way round I use to construct and init my UObjects in one call.
In one sentence: make a static function that takes in the desired parameters, creates the UObject, inits it with the params and returns it at the end.

For example, I have this UWeapon that extends UObject and I want to create a big list of them to add to the inventory, I can do so with:

Inventory.insert(UWeapon::MAKE(EWeaponType::HSword, "BlameGT", FWeaponDmg(20)));
Inventory.insert(UWeapon::MAKE(EWeaponType::HSword, "Pity", FWeaponDmg(20)));
Inventory.insert(UWeapon::MAKE(EWeaponType::Sword, "Hemorragy", FWeaponDmg(20)));
Inventory.insert(UWeapon::MAKE(EWeaponType::Sword, "StraightKatana", FWeaponDmg(20)));

Instead of:

UWeapon * weapon = NewObject<UWeapon>();
weapon.init(...params...);
Inventory.add(weapon);

In my Weapon.h I define:

static UWeapon* MAKE(EWeaponType wepType, FString name, FWeaponDmg wepDmg);

In Weapon.cpp i implement:

   UWeapon* UWeapon::MAKE(EWeaponType wepType, FString name, FWeaponDmg wepDmg){
        UWeapon* w = NewObject<UWeapon>();// UWeapon();
        w->init(wepType, name, wepDmg);
        return w;
}

Hope it helped :wink:

5 Likes