Serializing a Function in Unity using AnimationCurve

Hey there guys, I'm working on a game with Unity right now and I have a few classes which basically represent certain types of functions that I want to use in some contexts. What i would like to know is if there is a way to translate my functions into animation curves (ideally using a custom attribute such as SerializeCurveAttribute) so that I can use Unity's built-in serialization for said curves. I'm not quite sure how to go about this, as I've barely written any attributes, and the decompiled code for Unity's SerializeField literally contains nothing. Here is the code for my curve classes:
public interface ICurve
{
float Evaluate(float t);
}

public struct NormalCurve : ICurve
{
readonly float width;
readonly float maxValue;
readonly float minValue;

public NormalCurve(float width, float min, float max)
{
this.width = width;
maxValue = max;
minValue = min;
}

public float Evaluate(float value)
{
return Mathf.Max(
Mathf.Exp(-Mathf.Pow(value, 2f) / width) * (maxValue - minValue) +
minValue - 0.01f,
minValue);
}
}

public struct PropulsionCurve : ICurve
{
public float maxVelocity;
public float maxForce;

private readonly float coefficient;

public PropulsionCurve(float v_max = 100f, float f_max = 5f)
{
maxVelocity = v_max;
maxForce = f_max;
coefficient = f_max / (v_max * v_max);
}

public float Evaluate(float x) => Mathf.Min(coefficient * x * x, maxForce);
}
public interface ICurve
{
float Evaluate(float t);
}

public struct NormalCurve : ICurve
{
readonly float width;
readonly float maxValue;
readonly float minValue;

public NormalCurve(float width, float min, float max)
{
this.width = width;
maxValue = max;
minValue = min;
}

public float Evaluate(float value)
{
return Mathf.Max(
Mathf.Exp(-Mathf.Pow(value, 2f) / width) * (maxValue - minValue) +
minValue - 0.01f,
minValue);
}
}

public struct PropulsionCurve : ICurve
{
public float maxVelocity;
public float maxForce;

private readonly float coefficient;

public PropulsionCurve(float v_max = 100f, float f_max = 5f)
{
maxVelocity = v_max;
maxForce = f_max;
coefficient = f_max / (v_max * v_max);
}

public float Evaluate(float x) => Mathf.Min(coefficient * x * x, maxForce);
}
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?