I am trying to make a reload mechanism in Unity, but the function is in a scriptable object. This means I cannot use Coroutine as it is in MonoBehaviour. I could think of solving with a simple timer with Time.time and Time.deltaTime but for that, I should call the function every frame which seems not too right for me, I'd like to avoid this solution.
I thought about using C#'s built-in Async Await functions but I never used it before and it's quite confusing, I have no idea how to implement it after looking at Microsoft's documentation. I've tried implementing it but I always get an error saying
The body of 'Weapon.Reload()' cannot be an iterator block because 'void' is not an iterator interface type
I've done a coroutine implementation so it's easier to see what I want to achieve using Async/Await.
public virtual IEnumerator Reload()
{
if (currentMagazine == magazineSize)
yield break;
if (!reloading)
{
Debug.Log("Started reloading");
reloading = true;
}
else
{
yield return new WaitForSeconds(reloadTime);
currentMagazine = magazineSize;
reloading = false;
Debug.Log("Reload time over");
}
Debug.Log("Finished reloading");
yield break;
}
I want to be able to call this function and just let it do its job over time, without stopping code execution. At first, I tried the simple timer solution with a while loop then realized that just stops code execution so it's not working properly.
How could I do this using C#'s Async/Await?