• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by HLo · Jul 22, 2016 at 08:17 AM · gameobjectcoroutinesaddcomponent

How can I stop coroutine from another script file?

I have read the answers already given for similar problems but unable to find a solution. I have a coroutine in one script file, which I want to stop from another script file based on certain condition. Please guide me what I'm doing wrong. I have little experience with Unity. I'm getting this message when I play the game: "NullReferenceException: Object reference not set to an instance of an object GameController.Start () (at Assets/Scripts/GameController.cs:18)".

First script with the start coroutine is this:

 using UnityEngine;
 using UnityEngine.UI;
 using System.Collections;
 
 public class GameController : MonoBehaviour {
 
     public Camera cam;
     public GameObject[] balls;
     private float maxWidth;
 
     // Use this for initialization
     void Start () {
         if (cam == null) {
             cam = Camera.main;
         }
         Vector3 upperCorner = new Vector3(Screen.width, Screen.height, 0.0f);
         Vector3 targetWidth = cam.ScreenToWorldPoint(upperCorner);
         float ballWidth = balls[0].GetComponent<Renderer> ().bounds.extents.x;
         maxWidth = targetWidth.x - ballWidth;
         StartCoroutine (Spawn ());
 
     }
     
     public IEnumerator Spawn () {
         yield return new WaitForSeconds (2.0f); 
         while (true) {
             GameObject ball = balls [Random.Range (0, balls.Length)];
             Vector3 spawnPosition = new Vector3 (Random.Range (-maxWidth, maxWidth), transform.position.y, 0.0f);
             Quaternion spawnRotation = Quaternion.identity;
             Instantiate (ball, spawnPosition, spawnRotation);
             yield return new WaitForSeconds (Random.Range (1.0f, 2.0f));
         }
 
     }
 
     public void GameEnd () {
 
         StopCoroutine (Spawn ());
     
     }
 }

and the script from where I'm trying to stop it is this:

 using UnityEngine;
 using UnityEngine.UI;
 using System.Collections;
 
 public class DestroyOnContact : MonoBehaviour {
 
     public GameObject gameOverText;
     public GameObject restartButton;
 
 
 
     void OnTriggerEnter2D (Collider2D other) {
         if (other.gameObject.tag != "Zero")
         {
             StartCoroutine (GameOver ());
         }
             
         GameController gc = gameObject.AddComponent<GameController> ();
         gc.GameEnd ();
         Destroy (other.gameObject);
     }
 
     IEnumerator GameOver () {
 
         yield return new WaitForSeconds (1.0f);
         gameOverText.SetActive (true);
         restartButton.SetActive (true);
     }
 
 }
 
 
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by Bunny83 · Jul 22, 2016 at 09:06 AM

This will never work:

 StopCoroutine (Spawn ());

When you call "Spawn()" it returns a statemachine object which you initially pass to StartCoroutine. Here when you call Spawn again you create a new seperate object which doesn't run as a coroutine. So StopCoroutine can't stop anything.

You have to save your "Coroutine" instance when you create it and use that in StopCoroutine:

 private Coroutine gameCoroutine = null;
 
 
 void Start()
 {
     // [ ... ]
     gameCoroutine = StartCoroutine (Spawn ());
 }
 
 public void GameEnd ()
 {
     if (gameCoroutine != null)
         StopCoroutine (gameCoroutine);
 }

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image HLo · Jul 23, 2016 at 06:19 AM 0
Share

@Bunny83 Thanks for taking time to explain. I've tried the solution you provided but unfortunately, I'm still getting the same error message and the coroutine does not stop when called from second script using "gc.GameEnd();" as the balls continue to fall. Do I need to somehow change the code in the other script too?

avatar image HLo · Jul 24, 2016 at 07:02 PM 0
Share

@Bunny83 Your solution finally worked for me. Thanks a lot. It was my mistake not to have attached "Public GameController" to "DestroyOnContact" in the inspector. When I did, it worked.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Null Reference at (wrapper managed-to-native) 0 Answers

Photon Instantiate a prefab and add script on it. 1 Answer

Add instantiated class to gameobject 1 Answer

using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers

How to add component to a child of gameobject 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges