09 Object Lists
Last updated
Last updated
This example shows you how to use object lists in a blackboard.
These files can be found in the /Examples/[example] and /Blackboards/Examples folders.
using System;
using System.Collections.Generic;
using System.Linq;
using CrashKonijn.Blackboard.Contracts;
namespace BlackboardsLite
{
[Serializable]
public class SerializedChange
{
public int amount;
}
[Serializable]
public partial class SignalChange : ISomeAreSignals
{
[Signal]
private int amount;
[Signal]
private string name;
}
public partial class ObjectListBlackboard : BlackboardBehaviour
{
private int startHealth = 100;
// Lists can be of any type
private List<SerializedChange> serializedChanges;
private List<SignalChange> signalChanges;
// This is a computed property, showing health being equal to startHealth plus the sum of all changes.
private static int serializedHealth(Signals.StartHealth startHealth, Signals.SerializedChanges changes) => startHealth.Value + changes.Value.Sum(x => x.amount);
// WARNING: even though the type here has signals on its own. Change events are triggered by the VALUE of the signal.
// This means that even when changing the amount of a SignalChange, the containing list won't trigger an event.
private static int signalHealth(Signals.StartHealth startHealth, Signals.SignalChanges changes) => startHealth.Value + changes.Value.Sum(x => x.Amount);
}
}
using BlackboardsLite;
using CrashKonijn.Blackboard.Contracts;
using UnityEngine;
namespace CrashKonijn.BlackboardPro.Examples._09_object_lists
{
[RequireComponent(typeof(ObjectListBlackboard))]
public class ObjectListsHealthBehaviour : MonoBehaviour
{
/* Simple hack to show a button in the editor */
[Header("Removes 10 health.")]
[Button(nameof(DoDamage))]
public string doDamageButton;
/* Simple hack to show a button in the editor */
[Header("Adds 10 health")]
[Button(nameof(Heal))]
public string healButton;
/* Simple hack to show a button in the editor */
[Header("Clears the changes list")]
[Button(nameof(Clear))]
public string clearButton;
private ObjectListBlackboard blackboard;
public ObjectListBlackboard Blackboard
{
get
{
if (this.blackboard == null)
{
this.blackboard = this.GetComponent<ObjectListBlackboard>();
}
return this.blackboard;
}
}
public void DoDamage()
{
this.Blackboard.SignalChanges.Add(new SignalChange
{
Amount = -10
});
this.Blackboard.SerializedChanges.Add(new SerializedChange
{
amount = -10
});
}
public void Heal()
{
this.Blackboard.SignalChanges.Add(new SignalChange
{
Amount = 10
});
this.Blackboard.SerializedChanges.Add(new SerializedChange
{
amount = 10
});
}
public void Clear()
{
this.Blackboard.SignalChanges.Clear();
}
}
}