Last active
December 10, 2015 14:38
-
-
Save ViteFalcon/4448868 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment