Download

Using UPROPERTY in a class inside another?

I was working on some stats for my character like Hunger, Thirst and i made this code


#pragma once

class FHunger
{
public:

	FORCEINLINE float GetHunger() const { return Hunger; };
	FORCEINLINE void SetHunger(float NewHunger) { Hunger = NewHunger; };

	FORCEINLINE float GetMaxHunger() const { return MaxHunger; };
	FORCEINLINE void SetMaxHunger(float NewMaxHunger){ MaxHunger = NewMaxHunger; };

	UPROPERTY(EditDefaultsOnly, Category = Hunger)
		float DeadlyLevel;

	UPROPERTY(EditDefaultsOnly, Category = Hunger)
		float DamageRate;

protected:

	UPROPERTY()
		float Hunger;

	UPROPERTY(EditDefaultsOnly, Category = Hunger)
		float MaxHunger;
};

And then i use it inside a character like this:



	FHunger* Hunger;


But the UPROPERTY variables like DamageRate, MaxHunger doesn’t appear in Blueprint so i can’t edit them with Blueprints. Is there any way i can do that?

Hello.

FHunger should be derived from UObject. You should provide “EditInlineNew” keyword to UCLASS macro, this is to make this class editable as instance.
Hunger variable should be UPROPERTY with an “Instanced” keyword and be initialized as subobject. Instanced keyword allows you to edit an instance of the object right in place, instead of replacing it with another object. This is what you’re trying to achieve, if i get it right.

So, just like that, in character class declaration:



UPROPERTY(EditDefaultsOnly, Instanced, Category = Hunger)
UHunger* Hunger;


and in character class constructor:



Hunger = CreateDefaultSubobject<UHunger>(this, TEXT("Hunger"));


Yes, that’s exactly what i wanted! Thanks a lot =)

On the other hand, based on that example of yours, it sounds like you might be better served by a USTRUCT. UStructs are much more lightweight than UObjects, so unless you really need the capabilities of the latter, keep that in mind.

-Camille