# Achievements

```csharp
using Databrain.Stats;

public class StatsAchievement : DataObject {}
```

The achievements data type lets you easily create unlockable achievements. Simply define the max score an achievement must reach to get unlocked. Use the following API to add points and listen to an unlocked event:

<div align="left"><figure><img src="https://2348672745-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIoqF5QAgQsqxrjmTIKpE%2Fuploads%2F55cdt1oQKCAGLGvWtQUU%2FstatsAchievement.png?alt=media&#x26;token=1f24a8ec-4bc8-4f1e-bb0d-82f93371dd1f" alt=""><figcaption></figcaption></figure></div>

1. Create a new achievement data object.
2. Assign the total score and create a new OnAchievementUnlocked event.

{% hint style="info" %}
Stats add-on comes with a dedicated StatsEvents type which contains either the unlcoked achievement, a new value or a new progression.
{% endhint %}

3. OPTIONAL: If you have installed the Logic add-on, you can also add a custom logic which gets called on achievement unlocked.

<div align="left"><figure><img src="https://2348672745-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIoqF5QAgQsqxrjmTIKpE%2Fuploads%2F6uqtj65ODqULdxRTnNE5%2FstatsAchievementLogic.png?alt=media&#x26;token=cecce86d-4aeb-4715-b7c9-029d808e3de6" alt=""><figcaption><p>Optional, only if Logic add-on is installed</p></figcaption></figure></div>

## API

### Add achievement points

**AddPoints(int \_points);**

```csharp
public class AddAchievementPoints : MonoBehaviour    
{
    public DataLibrary data;
    
    [DataObjectDropdown("data")]
    public StatsAchievement achievement;
    
    public int points;

    // Directly add points to the achievement.
    // Do not worry about initial or runtime data. The points are automatically added
    // to the runtime data object
    public void AddPoints()
    {
        achievement.AddPoints(points);
    }
}
```

The points are automatically added to the runtime data object of the achievement data object.

### OnAchievementUnlocked

Listen to the StatsEvents OnAchievementUnlocked

```csharp
public class UIAchievement : MonoBehaviour
{
    public DataLibrary data;

    [DataObjectDropdown("data")]
    public StatsEvents OnAchievementUnlocked;
        
    public void Start()
    {
        data.OnDataInitialized += DataReady;
    }

    void DataReady()
    {
        // Register to the event
        OnAchievementUnlocked.RegisterListener(NewAchievement);
    } 
    
    // New achievement has been unlocked
    void NewAchievement(StatsEventData _data)
    {
        var _newAchievement = _data.newAchievement;
        Debug.Log("Achievement unlocked: " + _newAchievement.title);
    }

}
```

### CurrentScore

Get the current score of the achievement

### IsUnlocked

Get whether achievement is unlocked or not.
