- Home /
How to stop all StopAllCoroutines(); from another script
Hi! I got a cloning script provided by forums and I want to stop all coroutines after 35 seconds. But when I do that in the script it does not work. Is there any way to do this by stopping all coroutines via another script? Or do I just have to move it? Please let me know, here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class clonefor4 : MonoBehaviour
{
public GameObject MyObjectToClone;
Vector3 offset = new Vector3(2, 0, 2);
// Start is called before the first frame update
void Start()
{
StartCoroutine("Spawner");
}
IEnumerator Spawner()
{
while (true)
{
GameObject clone = Instantiate(MyObjectToClone, transform.position + offset, Quaternion.identity);
clone.transform.position = new Vector3(clone.transform.position.x, 8f, clone.transform.position.z);
clone.transform.position = transform.position + offset;
clone.transform.position = new Vector3(clone.transform.position.x, 4f, clone.transform.position.z);
**yield return new WaitForSeconds(35);
StopAllCoroutines();**
}
}
}
Thanks!
EDIT: Reormatted by Captain_Pineapple
Can you explain what exactly your trying to accomplish with this code?
Thanks for replying! The only real thing that matters in the code is yield return new WaitForSeconds(35) StopAllCoroutines();
If I take it out the game crashes if I turn on the script. I want to move my code somewhere so the cloning script does not have that code I mentioned earlier but still functions in the same way, it clones for 35 secs and then stops all coroutines. Hope this helps, Thanks!
Thank you Captain_Pineapple, I don't know how to format here, so thanks for helping me out so much!
Answer by Anis1808 · Dec 23, 2019 at 04:42 PM
In your other file create a List of coroutines that are running public List<Coroutine> all_coroutines;
, then in each coroutine you start, add its instance to the list all_coroutines.Add(StartCoroutine(AnyCoroutine()));
.
Finally, in the script you published, access the script in whatever way you want and create a foreach loop to stop the coroutines
MySript script = // GetComponent or FindObjectOfType;
foreach(Coroutine cor in all_coroutines){
StopCoroutine(cor);
}
Your answer
Follow this Question
Related Questions
how to only get the negative or positive part of a GetAxis 1 Answer
How do I stop my character from sliding after adding force? 0 Answers
Does anyone know how to activate different scripts OnTrigger? 1 Answer
How to clone on collision 0 Answers
3D / Top-Down - Make a script to let the player zoom the camera in and out 0 Answers