public
Last active

  • Download Gist
Game Object Attributes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
namespace Component
{
extern const char* HEALTH;
extern const char* NAME;
}
 
template <const char* Name, typename T>
class Attribute
{
private:
const std::string mName;
Object& mObject;
T* mValue;
public:
Attribute(Object& object)
: mName(Name)
, mObject(object)
, mValue(object.getData<T>(Name))
{
}
std::string getName() const
{
return mName;
}
Object& getObject() const
{
return mObject;
}
const Object& getObject() const
{
return mObject;
}
operator bool() const
{
return mValue != 0;
}
Attribute& operator = (const T& val)
{
if (mValue)
mValue = val;
return *this;
}
T value() const
{
if (mValue)
return *mValue;
throw std::exception("This attribute doesn't exist for object.");
}
T value(const T& defaultValue) const
{
if (mValue)
return *mValue;
return defaultValue;
}
};
 
typedef Attribute<Component::HEALTH, long> HealthAttribute;
typedef Attribute<Component::NAME, std::string> NameAttribute;
 
// In a CPP file.
namespace Component
{
const char* HEALTH = "health"; // or a UUID
const char* NAME = "name";
}
 
// USAGE
// =====
HealthAttribute health(myGameObject);
 
// Usage: Without caring if the attribute exists for the game object
long healthValue = health.value(0);
healthValue -= 100;
health = healthValue; // NOTE: The value doesn't get set if myGameObject doesn't have health.
 
// Usage: Check if the attribute exists and then do something
if (!health) {
NameAttribute name(myGameObject);
name = std::string("This ain't alive!");
} else if (0 == health.value()) {
NameAttribute name(myGameObject);
name = std::string("He's dead, Joe!");
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.