2

I have a struct which holds animation data. In the struct i have a method to change the animation time but for some reason the value never actually changes. Not sure i understand why that is the case.

public struct AnimationCommand
{
    float _duration;
    Action _onCompleteCallback;
    Action<float> _onUpdateCallback;

    public float Duration => _duration;

    public AnimationCommand(float animationTime, Action onComplete = null, Action<float> onUpdate = null)
    {
        _duration = animationTime;
        _onCompleteCallback = onComplete;
        _onUpdateCallback = onUpdate;
    }

    public void SetDuration(float animationTime) => _duration = animationTime;
}

In my class i have this:

    /*AnimationData is a property in base class 

    [SerializeField]
    AnimationCommand _animationData;
    protected AnimationCommand AnimationData => _animationData;
    */

    float delta = 10; //test value
    AnimationData.SetDuration(delta);
    Debug.Log(delta + " :: " + AnimationData.Duration);

The output i get is 10 :: 0

Why does it not change the value? I assumed calling the method on the struct would change the value and avoid the value copy semantics that structs have ? Am i wrong here?

WDUK
  • 1,412
  • 1
  • 12
  • 29
  • Does this answer your question? [Public variable of struct is not changing](https://stackoverflow.com/questions/31127088/public-variable-of-struct-is-not-changing) – Charlieface May 19 '23 at 10:28

1 Answers1

4

protected AnimationCommand AnimationData => _animationData;

this will return copy of the _animationData.
Therefore, AnimationData.SetDuration(delta); becomes as "get the copy and modify it". So, the original does not changed.

fana
  • 1,370
  • 2
  • 7
  • Ah i see, does properties support `ref` keyword at all? if not i guess i'll just make the backing field protected. – WDUK May 19 '23 at 01:37
  • I don't know about "property with `ref` keyword". But, I think, if you want to **refer** the object, using `class` instead of `struct` may be simple way. Or, the base class could provide method/property which call `_animationData.SetDuration()`. – fana May 19 '23 at 01:44
  • 2
    Structs are _Value Types_. It's best to make Value types _immutable_. This is, as you found out, because they spin of copies during assignment (and similar operations). Use a class (a reference type) instead. – Flydog57 May 19 '23 at 02:46
  • I need to use structs because in unity their ECS / Job System is entirely struct based and does not use classes. – WDUK May 19 '23 at 23:21