Skip to content
This repository has been archived by the owner on Aug 13, 2022. It is now read-only.

Custom Attributes

Sahil Jain edited this page Apr 21, 2021 · 2 revisions

Attributes created this way are fairly simple, and may not be suitable for more complex games. For example, what if our game had characters with Armour, which was dependent on another stat, Agility? We can create novel types of attributes by subclassing AttributeScriptableObject and overriding the CalculateInitialValue and/or CalculateCurrentAttributeValue methods.

In this repository, we have three primary attributes: Strength, Agility, Intelligence, which are all assets of AttributeScriptableObject. We also have numerous other stats that are a linear function of one of these stats - for example, the Armour stat is a linear function of Agility, given by the formula: 0.17 * Agility + 4.

We can achieve this by creating a new class that derives from AttributeScriptableObject:

[CreateAssetMenu(menuName = "Gameplay Ability System/Linear Derived Attribute")]
public class LinearDerivedAttributeScriptableObject : AttributeScriptableObject
{
    public AttributeScriptableObject Attribute;
    [SerializeField] private float gradient;
    [SerializeField] private float offset;

    public override AttributeValue CalculateCurrentAttributeValue(AttributeValue attributeValue, List<AttributeValue> otherAttributeValues)
    {
        // Find desired attribute in list
        var baseAttributeValue = otherAttributeValues.Find(x => x.Attribute == this.Attribute);

        // Calculate new value
        attributeValue.BaseValue = (baseAttributeValue.CurrentValue * gradient) + offset;

        attributeValue.CurrentValue = (attributeValue.BaseValue + attributeValue.Modifier.Add) * (attributeValue.Modifier.Multiply + 1);

        if (attributeValue.Modifier.Override != 0)
        {
            attributeValue.CurrentValue = attributeValue.Modifier.Override;
        }
        return attributeValue;
    }
}

This new type of attribute allows us to define attributes using the straight-line equation y = mx + c, allowing us to create attributes which are a linear function of another attributes.

Alternatively, we could have used a AnimationCurve property to calculate the stat, or a CSV file containing the data.

Clone this wiki locally