I'm working on a timed event controller, here is the code (feel free to use it): Code (CSharp): //Libraries using System.Collections.Generic; using UnityEngine; //Package that contains info about the event and how //long it will last public struct actionEvent { public System.Action action; public float timeLeft; public actionEvent (System.Action _action, float _totalTime) { this.action = _action; this.timeLeft = _totalTime; } public bool Run (float timepassed) { this.timeLeft -= timepassed; Debug.Log(timeLeft); if (timeLeft > 0) { action(); return false; } else { return true; } } } //If an agent requires an event to occur during a certain time //They will resort to this controller public class eventController : Controller<eventController> { //List with all occuring events protected static List<actionEvent> events = new List<actionEvent>(); public void Start() { //Start singleton service ActivateSingleton(this); } public static void subscribe (System.Action _action, float _totalTime, bool _overwrite = true) { actionEvent newAction = new actionEvent(_action, _totalTime); events.Add(newAction); } void FixedUpdate () { float delta = Time.smoothDeltaTime; for (int i = 0; i < events.Count; i++) { bool dumpEvent = events[i].Run(delta); if (dumpEvent) { events.RemoveAt(i); } } } } The thing is, if I use actionEvent as a class, the time left counts correctly, going -0.02f everytime. But if I use actionEvent as struct, time left keeps stuck at the first decrement. This seems like a bug, could anyone explain me, why this happens?
Got what's going wrong, structs are always passed by value (never by reference), so when I do this: Code (CSharp): bool dumpEvent = events[i].Run(delta); CSharp makes a copy of events and run it, it's not the same from the list I created, the workaround I found is this: Code (CSharp): actionEvent e = events[i]; bool dumpEvent = e.Run(delta); events[i] = e;