0

This is my struct

public struct Timer
{
    private readonly float _duration;

    public float Time { get; private set; }

    public Timer(float duration)
    {
        _duration = duration;
        Time = duration;
    }

    public void Tick(float deltaTime)
    {
        if (Time == 0)
            return;
        
        Time -= deltaTime;

        if (Time < 0)
            Time = 0;
    }

    public void Reset()
    {
        Time = _duration;
    }

}

It can be used by a class like so

public class Level : MonoBehavior
{
    private Timer _timer = new Timer(10f);
    
    private void Update()
    {
        _timer.Tick();

        if (_timer.Time == 0)
        {
            print("Time's up!");
        }
    }

}

Since the struct only contains value types, does that mean it will automatically be allocated to the stack when it gets instantiated by the other class?

Sean Carey
  • 799
  • 5
  • 12
  • 5
    No, the class object is stored in the GC heap. – Hans Passant Dec 22 '20 at 19:19
  • yes, I guess however the method might cause an issue. have a look at https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/structs – Walter Verhoeven Dec 22 '20 at 19:20
  • 2
    In this context it will end up on the heap with the rest of the Level class. If it was, for example, a local variable inside a method it would be on the stack – Caius Jard Dec 22 '20 at 19:23

1 Answers1

3

This won't be allocated on the stack. All members of the class are heap allocated, regardless of whether they are value types or not.

ekke
  • 1,280
  • 7
  • 13
  • While this is mostly true, it's worth a deeper look at variable allocation: https://ericlippert.com/2010/09/30/the-truth-about-value-types/ – Enigmativity Aug 09 '22 at 05:29