- Home /
Starting a single coroutine when multiple methods use the same name.
I have an issue with a coroutine called BuildUnit written in my CreateUnit.cs script which is attached to my factory prefab. The problem is when I invoke the BuildUnit coroutine it invokes the same amount of times that I have the number of factory prefabs instantiated as gameobjects.
Heres the code for queuing and dequeing the BuildUnit coroutine:
void Update () {
// Check if unit manager contains factory structure
if (Input.GetKeyDown(KeyCode.Q)) {
foreach (GameObject unit in unitManager.GetSelectedUnits()) {
// Check if player pressed q while selected on factory
if (unitManager.GetSelectedUnits()[0].tag == "Factory") {
// Queue each production cylce
queue.Enqueue(() => {
StartCoroutine("BuildUnit");
});
}
}
}
// TODO: check for input for other units and structures
if (queue.Count > 0 && !isBuilding) {
queue.Dequeue().Invoke();
isBuilding = true;
}
}
Can you post the rest of your code and describe the problem more detailed?
Why are you cycling all selected units? Also, is it possible that GetSelectedUnits() returns all your factories, and not just the selected ones? That would be causing your issue.
Also, in line 6, why are you only checking if the first selected unit is a factory? Surely it should be if(unit.tag =="Factory"), to check if the current unit in the foreach loop is a factory or not.
GetSelectedUnits only returns one factory if I click one factory. The problem seems to be the StartCoroutine calls the BuildUnit function as many times as there are written instances of it. I.$$anonymous$$ there are 3 factories, so StartCoroutine("BuildUnit") is called 3 times. Is there any way to just Start one coroutine for that specific script?
Well your foreach loop handles how many times StartCoroutine is called in the code you provided. If its called 3 times, that means there were 3 units in GetSelectedUnits().
Or, there's something with the queue.Enqueue(). Recursion perhaps? I have no way of knowing because you never show what queue is.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer
Audio mixer Setfloat() method problem in coroutine 0 Answers
Help with waiting / coroutine c# 1 Answer