Reference to Coroutine from within itself like a 'this' keyword but for a specific routine.
Say I have a bunch of workers who needs to collect wood. When they interact with a tree, it will start a coroutine with a progress variable that increases incrementally. Before each increment the routine need to check whether the worker is still working on the task, or the routine will end.
I have made a Coroutine variable on the units controller, that stores which task/routine the unit is on, and my idea is to compare this value to the routine before each increment.
The issue is, I have no idea how to get the routine reference from within the script.
I tried to work around the issue by having a routine variable that is defined as the StartCoroutine Method, and then immediately referred to in the start of the coroutine.
This however is prone to error as it would be possible for two units to interact more or less the same time, resulting a the routine being changed before the first of these units can refer to it.
Any suggestions on how to deal with this problem?
here is my script:
public abstract class InteractableContinuous : Interactable
{
[Header("Continuous Interaction")]
[SerializeField]
private float tickFrequenzy= 0.1f;
private Coroutine routine;
public override void InteractedWith(UnitController interactor)
{
base.InteractedWith(interactor);
routine = StartCoroutine(ProgressRoutine(interactor));
}
public virtual IEnumerator ProgressRoutine(UnitController interactor)
{
Coroutine interactionRoutine = routine;
while (interactor.interactionRoutine == interactionRoutine)
{
DoStuff();
yield return new WaitForSeconds(tickFrequenzy);
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613005424im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Persistent Timers in Couroutines 0 Answers
Issues with video player coroutine 2 Answers
Co-routine a recursion help 0 Answers
Create events that fires off a coroutine from another script 0 Answers