Skip to content

@ViteFalcon /Game Object Attributes
Last active

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.