Hello! I have some prefabs being instantiated and the speed at which they fall increases over time using InvokeRepeating. Calling InvokeRepeating works great but my issue is that I can’t get it to stop…even when the game ends and you reload the scene, it picks up where it left off instead of resetting to start off slow and speed up again. I have been trying to use CancelInvoke but with no luck.
Here is my first attempt where I'm trying to use CancelInvoke:
using UnityEngine;
using System.Collections;
public class SpawnBox : MonoBehaviour
{
public GameObject[] boxList;
private bool gameOver;
public GameObject gameOverText;
public GameObject restartButton;
public GameObject menuButton;
void Start()
{
gameOver = false;
StartCoroutine(SpawnNewBox());
Speed();
}
void Speed()
{
InvokeRepeating ("changeGravity", 5.0f, 5.0f);
}
void changeGravity ()
{
Physics2D.gravity += new Vector2 (0, -2);
}
IEnumerator SpawnNewBox()
{
yield return new WaitForSeconds (1.75f);
while (!gameOver)
{
int i = Random.Range (0, boxList.Length);
Instantiate (boxList *, transform.position, Quaternion.identity);*
-
yield return new WaitForSeconds (Random.Range (2.0f, 3.1f));*
-
}*
GameObject.FindGameObjectWithTag(“MainCamera”).GetComponent().Stop();
GameObject.FindGameObjectWithTag(“Destroyer”).GetComponent().Play();
gameOverText.SetActive(true);
-
yield return new WaitForSeconds (1.5f);*
restartButton.SetActive(true);
-
menuButton.SetActive (true);*
-
CancelInvoke ();*
}
public void GameOver()
{
gameOver = true;
}
}
I wasn’t exactly sure if having InvokeRepeating and a Coroutine on the same script was causing an issue so I took out the Invokes and made a separate script here:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpeedUp : MonoBehaviour {
-
void Start ()*
-
{*
-
InvokeRepeating ("changeGravity", 5.0f, 5.0f);*
-
}*
-
void changeGravity ()*
-
{*
-
Physics2D.gravity += new Vector2 (0, -2);*
-
}*
}
I tried putting CancelInvoke(); in an Update function but that did nothing as well…I’ve been staring this in the face for awhile and hopefully a fresh pair of eyes can help out. Thank you in Advance!!!