Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Struct value won't change when calling a method

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading