Average#
Collections / Average
Can Read
Cannot Write
Description#
The mean value of every item of a collection read as a number
Parameters#
| Name | Description |
|---|---|
| Collection | The collection whose items are averaged |
Code#
using System;
using UnityEngine;
using VisualScript.Icons;
namespace VisualScript.Runtime
{
[Get]
[Title("Average")]
[Category("Collections/Average")]
[Description("The mean value of every item of a collection read as a number")]
[Image(typeof(IconSigma), ColorTheme.Type.Teal, typeof(BadgeHash))]
[Parameter("Collection", "The collection whose items are averaged")]
[Keywords("Mean", "Median", "Middle", "Total", "List", "Array")]
[Serializable]
public class TypeNumberCollectionAverage : TypeNumber
{
[SerializeField] private GetCollection m_Collection = new GetCollection();
public override double Get(Args args)
{
using Args scoped = Args.Get(args);
int count = this.m_Collection.Capture(scoped);
if (count == 0) return 0f;
double sum = 0f;
for (int i = 0; i < count; ++i)
{
if (ArgsCollectionParameters.TryGetItem(this.m_Collection, scoped, i, out double item))
{
sum += item;
}
}
return sum / count;
}
public override string ToString()
{
return $"Average of {this.m_Collection}";
}
protected override SubscriptionMode Subscription => SubscriptionMode.OnChange;
}
}