I have a set of spawn points and an object that I want to spawn from a random spawn point every second. I've used the InvokeRepeating function to make this work. But now, I want to modify the code a little bit. I don't want the the object to be spawned from the same spawn point twice in a row.
Let's say I have 5 spawn points: A, B, C, D, and E. When InvokeRepeating runs, the object is spawned randomly from spawn point C. So when InvokeRepeating runs again, I don't want the object to spawn at spawn point C. It has to randomly pick another spawn point. I don't want the object to spawn at at a particular spawn point twice in a row.
Here my code:
void Start ()
{
GameObject[] SP = GameObject.FindGameObjectsWithTag ("spawnPoint");
spawnPoints = new Transform[SP.Length];
for(int i=0; i < SP.Length; i++)
{
spawnPoints[i] = SP[i].transform;
}
InvokeRepeating("SpawnObject", spawnTime, spawnTime);
}
void SpawnObject()
{
int spawnPointIndex = Random.Range(0,spawnPoints.Length);
Instantiate(theObject, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}
Any idea what I can add to my code so solve this?
↧
Prevent object from spawning at a spawn point twice in a row?
↧
HOW TO INSTANTIATE IMAGE INSIDE CANVAS?
void start(){
InvokeRepeating ("starta",2, 2);
}
void starta(){
float x = Random.Range(-220f, 126f);
Vector3 da = new Vector3 (x,0,0);
GameObject s=Instantiate (canvas,transform.position,canvas.transform.rotation)as GameObject;
GameObject ss=Instantiate (imahe, da, Quaternion.identity)as GameObject;
ss.transform.SetParent(s.transform,false);
}
↧
↧
Invoke Ball Obstacle based on Score
In the beginning of my game there is one instantiated bouncing ball which works great. As the player earns points up to 3 balls may be present on the screen at one time. I have three separate ball spawners in my scene. One is activated right away and the others activate once a certain score is reached. My issue is that up to 5 balls appear on the screen. I have been working on my code for hours trying to figure out a way to destroy a ball if there are already three visible on the screen. I am getting closer, but am still struggling. I was hoping someone might have a suggestion.
Here's my code - Used for Getting the Ball Moving:
using UnityEngine;
using System.Collections;
public class BallScriptLeft : MonoBehaviour {
private Animator anim;
private Rigidbody2D rb;
public GameObject ball;
void Start(){
anim = GetComponent ();
rb = GetComponent ();
rb.velocity = new Vector2 (5f, 5f);
}
void Update(){
if (BallControllerLeft.bouncingBall == true) {
StartCoroutine (DestroyBall ());
}
if (ScoreManager.scoreCount >= 25000 && ScoreManager.scoreCount <= 50000) {
anim.speed = 1.2f;
}
if (ScoreManager.scoreCount >= 50000 && ScoreManager.scoreCount <=75000) {
anim.speed = 1.5f;
}
if (ScoreManager.scoreCount >= 75000 && ScoreManager.scoreCount <=100000) {
anim.speed = 1.8f;
}
}
void OnTriggerEnter2D(Collider2D target){
}
IEnumerator DestroyBall(){
yield return new WaitForSeconds (BallControllerLeft.bounceTime);
Destroy(ball);
BallControllerLeft.bouncingBall = false;
}
}
Code 2 - Used for Instatiating Ball:
using UnityEngine;
using System.Collections;
public class BallControllerLeft : MonoBehaviour {
public static int bounceTime;
public int spawnWait;
public Transform [] spawnPoints;
public GameObject ball;
private int ballCount = 0;
private int level=0;
public static int ballOnField=0;
public static bool bouncingBall=false;
void Start(){
}
void Update () {
if (ballCount == 1||BallBoxCollider.isDestroyed == true) {
StartCoroutine (OneBallAtATime ());
ballCount = 0;
BallBoxCollider.isDestroyed = false;
}
if (ScoreManager.scoreCount >= 25000 && ScoreManager.scoreCount <=50000 && level==0) {
level++;
bounceTime = 20;
spawnWait = 5;
InvokeRepeating("SpawnBall",spawnWait,spawnWait);
if (BallBoxCollider.isDestroyed == true) {
StartCoroutine (OneBallAtATime ());
level = 0;
}
//Invoke ("SpawnBall", spawnWait);
//StartCoroutine (OneBallAtATime ());
}
if (ScoreManager.scoreCount >= 50000 && ScoreManager.scoreCount <=75000) {
bounceTime = 30;
}
if (ScoreManager.scoreCount > 75000) {
bounceTime = 40;
}
}
void SpawnBall(){
ballCount=1;
ballOnField++;
bouncingBall = true;
Debug.Log ("SpawnBall Active");
int spawnIndex = Random.Range (0, spawnPoints.Length);
//int objectIndex = Random.Range (0, ball.Length);
Instantiate (ball, spawnPoints [spawnIndex].position, spawnPoints [spawnIndex].rotation );
}
IEnumerator OneBallAtATime(){
Debug.Log ("Left Ball Spawned");
CancelInvoke ("SpawnBall");
yield return new WaitForSeconds (bounceTime);
Debug.Log ("Left Ball Spawning");
ballOnField = 0;
InvokeRepeating("SpawnBall",spawnWait,spawnWait);
}
}
Code 3 - Used for Destroying Ball:
using UnityEngine;
using System.Collections;
public class BallBoxCollider : MonoBehaviour {
public GameObject ball;
public static bool isDestroyed=false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (BallController.ballOnField > 1||BallControllerLeft.ballOnField > 1||BallControllerTop.ballOnField > 1) {
Destroy (ball);
}
}
void OnTriggerEnter2D(Collider2D other){
if (other.tag == "Player") {
BallController.ballOnField = 0;
isDestroyed = true;
Destroy (ball);
Debug.Log ("Collision Detected");
}
}
}
↧
Coroutine in place of InvokeRepeating in need of start at time parameter
IEnumerator SendSpriteForward(int no, Coroutine n,int prevhighestorderInlayer)
{
while (true) {
StopCoroutine (n);
for (int i = 0; i < gameObjectsContainer.transform.childCount; i++) {
gameObjectsContainer.GetChild (i).transform.GetChild (no).GetComponent ().sortingOrder = gameObjectsContainer.GetChild (i).transform.GetChild (prevhighestorderInlayer).GetComponent ().sortingOrder + 1;
}
n = StartCoroutine (GenericCoroutine (no, 0));
yield return new WaitForSeconds (6);
}
}
I need to call this coroutine in start method at different times .
In start Method i want to call them as such
StartCoroutine(SendSpriteForward(5,one,0)); //start this call at 6 second
StartCoroutine(SendSpriteForward(4,two,5)); // this at 7
StartCoroutine(SendSpriteForward(3,three,4));//8
StartCoroutine(SendSpriteForward(2,four,3));//9
StartCoroutine(SendSpriteForward(1,five,2));//10
StartCoroutine(SendSpriteForward(0,six,1));//11
and so .
The Repeating functionality has been attained but the start time i need to.
Thank you.
↧
Increase speed every 5 seconds
Why would this not work?
public static float speed = -5f;
public Vector2 obstacleVelocity = new Vector2(0.0f, speed);
public Rigidbody2D rb;
// Use this for initialization
void Start()
{
InvokeRepeating("IncreaseSpeed", 3, 1);
rb.velocity = obstacleVelocity;
transform.position = new Vector3(Random.Range(transform.position.x - 2.2f, 2.2f), transform.position.y + 2, transform.position.z);
}
void Update()
{
Destroy(gameObject, 5);
}
void IncreaseSpeed()
{
speed = speed - 5f;
}
I know there is a number of ways to do this, but what I tried to do is assign the Y value to -5, and then icrease Y (speed) every 3 seconds for -0.3f. It doesn´t seem to work, the objects are not getting any faster.
Thanks!
↧
↧
if and invoke repeating in start...
This is my obstacle spawning code:
public GameObject Obstacles;
float gameTime;
void Start()
{
gameTime = Time.timeSinceLevelLoad;
InvokeRepeating("CreateObstacle", 1f, 1.25f);
}
void Update()
{
}
void CreateObstacle()
{
Instantiate(Obstacles);
}
Now what I want to do is InvokeRepeat 1F, 1.25F only when gameTime > 0 && gameTime <= 46.
And InvokeRepeat 0.25f, 0.85f when gameTime > 46.
I have no idea how to do this, beceause if I´d try to make couple if statements they would never update beceause they have to be called in Start() right?
Thanks!
↧
My script keeps crashing my Unity Editor Client. Please help
So I created this script recently to spawn a "enemyPrefab" every x seconds. But when the function is called on my Unity client just crashes and I have to open up Task Manager and manually End Task it for it to close.
Here's my script:
#pragma strict
//Variable list
public var spawner : Transform[];
public var spawnTime : float;
public var enemyPrefab : GameObject;
private var spawner_num : int;
function Start ()
{
//Call the SpawnEnemy function every spawnTime seconds
InvokeRepeating ("SpawnEnemy", spawnTime, spawnTime);
}
function SpawnEnemy ()
{
//Tells the log that the function has been called upon
Debug.Log("Started");
while (true)
{
//Picks a random spawner to spawn "enemyPrefab" out of
spawner_num = Random.Range(0,3);
//Tells log what spawner has been picked
Debug.Log("Spawner is spawner number " + spawner_num);
//Spawns the "enemyPrefab" at the spawner location
Instantiate(enemyPrefab, spawner[spawner_num].position, spawner[spawner_num].rotation );
}
//Tells the log the function has ended.
Debug.Log("Ended");
}
Thank you so much if you can help me out on this, I've been trying to advance my game for about 30 minutes now googling this topic but can't find the answer, but anything helps! :)
(P.S. I'm on Windows if that helps any.)
↧
Displaying C# Int Value to GUI
Hey all,
I'm starting a new project and I'm trying to create a date function where every seconds adds another day. So far, my code is:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class date : MonoBehaviour {
public int day;
void dayAdd () {
day++;
}
void Start () {
InvokeRepeating ("dayAdd", 0f, 1.0f);
}
}
Now I'm trying to show this int value to a UI. I haven't found any method that particularly works for me, so I would love some help!
Thanks!
↧
InvokeRepeating() not working.
I am trying to fire bullets at a rate determined by the weaponFireRate variable, but no matter what I do it will always fire one bullet per seconds. Here is the code:
public int health;
public int playerSize;
public int weaponDamage;
public float weaponFireRate = 10.0f;
public int bulletSpeed = 10;
public int bulletSize;
public GameObject bullet;
private bool shooting = false;
// Use this for initialization
void Start () {
InvokeRepeating("Shoot", 0.0f, (1.0f / weaponFireRate));
}
// Update is called once per frame
void Update () {
shooting = false;
if (Input.GetButton("Fire1"))
{
Shoot();
shooting = true;
}
}
void Shoot()
{
if (!shooting) return;
GameObject bulletClone;
bulletClone = Instantiate(bullet, transform.position, transform.rotation);
bulletClone.GetComponent().AddForce(bulletClone.transform.up * bulletSpeed);
}
Any help would be greatly appreciated!
↧
↧
Decreasing a value over time, called by InvokeRepeating
I'm attempting to create an effect in my game in which two discreet spot lights lower and raise their intensity every so often to give the impression that the player is actually travelling through space.
The method I'm using does work to an extent;
void Start ()
{
InvokeRepeating("LightChange", 5, 30);
}
void LightChange()
{
if (Random.value >= 0.5f)
{
dirLight1.intensity -= (Mathf.Clamp(0.05f * Time.deltaTime, 0.00f, 0.5f));
dirLight2.intensity += (Mathf.Clamp(0.05f * Time.deltaTime, 0.00f, 0.5f));
}
else
{
dirLight1.intensity += (Mathf.Clamp(0.05f * Time.deltaTime, 0.00f, 0.5f));
dirLight2.intensity -= (Mathf.Clamp(0.05f * Time.deltaTime, 0.00f, 0.5f));
}
}
It works in that the function is called and the value for the light intensity does indeed change, although it only changes for a moment (from .5 to .45) whereas the intended effect is that the values would decrease/increase to their minimum/maximum respectively.
↧
Why aren't Coroutines working for me?
Hi, I was originally using InvokeRepeating for my enemies to spawn and it is fine if they spawn at a continuous rate but I want them to spawn faster and faster as the game goes on but since InvokeRepeating only happens on Start the variable spawnTime that decreases bit by bit doesnt change in the game.
I then researched and made it into a Coroutine that does what I need it to but if I start my Coroutine in Start only one enemy spawns right at the start and if i StartCoroutine in Update it spawns every frame.
There must be something wrong with my code but I have been scrutinising it four hours and can't find what is wrong.
Could you please help me locate the issue? I bless these problems since they are helping me to learn a lot more but when I need help I need help.
public GameObject enemy;
public float spawnTime;
public Transform[] spawnPoints;
void Start () {
StartCoroutine ("SpawnRepeat");
InvokeRepeating ("ChangeRate", 30, 30);
}
IEnumerator SpawnRepeat(){
Spawn ();
yield return new WaitForSeconds(spawnTime);
}
void Spawn(){
int spawnPointIndex = Random.Range (0, spawnPoints.Length);
Instantiate (enemy, spawnPoints [spawnPointIndex].position, spawnPoints [spawnPointIndex].rotation);
}
void ChangeRate(){
spawnTime -= 10f;
}
↧
Getting Updates from website
Im calling Functions on my mindstorms device running a webserver. it listens to numbers im sending e.g. 200 or 900 and drives a certain way. There is also a "motorstatus" url where the current motor position is shown. so calling that IP gives me a text with that number i could use for drawing something or just showing the current pos.
How can i call that url while my motor is running?
IEnumerator WaitForRequest(WWW www) //here i call the number e.g. 300
{
yield return www;
// check for errors
if (www.error == null)
{
// OK
}
else
{
// ERROR
}
}
in start im doing this:
InvokeRepeating("OutputTime", 1f, 1f);
Funktion:
IEnumerator WaitForStatus(WWW www) //call ip + motorstatus - should return numbers between 0 and 900
{
yield return www;
// check for errors
if (www.error == null)
{
textFromWWW = www.text;
Debug.Log(Time.time + " :: " + textFromWWW);
}
else
{
//Debug.Log("WWW Error: " + www.error);
}
}
Or is there a better way of getting a dynamic text from a website.
↧
Pause between user mouse clicks
I'm trying to make a grid turn based game and I want the user to be able to click on the grid, then have a pause function that does not let them click anywhere for 2 seconds or so then after this duration they can make another move. I've tried disabling the colliders on the grid I am using in the on mouse down event, then reenabling them using both Coroutine and invokerepeating with no luck. Is there a correct general way of either disabling clicking on screen or some other way of doing what I am intending?
Thanks!
↧
↧
invoke method attack.decreaseTimeRemaining couldn't be called
So the scene picks a random image of four, at which point I want a count down to start that is waiting for user input, if the countdown hits 0 the user dies if the correct input is pressed then they move to the next scene - no other errors in compiler just invoke can't be called. This is one example of an image chosen. Hope i didn't copy this poorly or make a stupid letter error. please help
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Attack : MonoBehaviour {
public float timeRemaining = 2.0f;
float num;
void state_AttackUp () {
InvokeRepeating ("decreaseTimeRemaining", 1.0f, 1.0f);
if (Input.GetKeyDown (KeyCode.UpArrow)) {
CancelInvoke ("decreaseTimeRemaining");
Application.LoadLevel("Level6");
} else if (timeRemaining == 0) {
Application.LoadLevel("Level7");
}
}
↧
Raycast ignoring InvokeRepeating intervals
Hi, so i posted a question to the default answers page but it's been under moderation for 2 days now so was advised to post my question here instead.
I'm fairly new to Unity and coding so bear with me but essentially I have 2 separate codes; the first is for the player to shoot when i hold down the "Fire1" key which works perfectly, and then there's this one which doesn't work so nicely...
I'm trying to add a raycast to my object so that whenever the player is in line of sight it invokes the "shooting" function, the actual raycast works but I believe that raycasts are once every tick so the code is getting invoked then cancelled repetitively causing it to shoot every frame instead of at the determined interval.
should i add a interval between the raycasts using boolean's so that it isn't every frame but instead at a determined interval? or do i need to change it from Update?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyShootingScript : MonoBehaviour {
public GameObject BulletEmitter;
public GameObject Bullet;
public float BulletForwardForce;
public float FireRateSeconds;
public GameObject Enemy;
private float rayDirection;
public float RayOffset;
void Raycast ()
{
RaycastHit hit;
if (Physics.Raycast (transform.position, transform.forward * RayOffset, out hit)) {
Debug.DrawRay(transform.position, transform.forward * RayOffset, Color.green, 2);
//print ("Something in line of sight");
print (hit.collider.gameObject.name);
if (hit.collider.gameObject.name == "Player")
{
//print ("Player in line of sight");
InvokeRepeating ("Shooting", .001f, FireRateSeconds);
}
else
{
CancelInvoke ("Shooting");
}
}
}
void Shooting ()
{
GameObject TemporaryBulletHandler;
TemporaryBulletHandler = Instantiate (Bullet, BulletEmitter.transform.position, BulletEmitter.transform.rotation) as GameObject;
TemporaryBulletHandler.transform.Rotate(Vector3.forward);
Rigidbody TemporaryRigidbody;
TemporaryRigidbody = TemporaryBulletHandler.GetComponent ();
TemporaryRigidbody.AddForce (transform.forward * BulletForwardForce);
Destroy (TemporaryBulletHandler, 3.0f);
}
}
Thanks in advance :) Pen
↧
Raycast ignoring InvokeRepeating intervals
Hi, so i'm fairly new to Unity and coding and am doing a project for college.
Essentially I have 2 separate codes; the first is for the player to shoot when i hold down the "Fire1" key which works perfectly, and then there's this one which doesn't work so nicely...
I'm trying to add a raycast to my object so that whenever the player is in line of sight it invokes the "shooting" function, the actual raycast works but I believe that raycasts are once every tick so the code is getting invoked then cancelled repetitively causing it to shoot every frame instead of at the determined interval.
should i add a interval between the raycasts using boolean's so that it isn't every frame but instead at a determined interval? or do i need to change it from Update?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyShootingScript : MonoBehaviour {
public GameObject BulletEmitter;
public GameObject Bullet;
public float BulletForwardForce;
public float FireRateSeconds;
public GameObject Enemy;
private float rayDirection;
public float RayOffset;
void Raycast ()
{
RaycastHit hit;
if (Physics.Raycast (transform.position, transform.forward * RayOffset, out hit)) {
Debug.DrawRay(transform.position, transform.forward * RayOffset, Color.green, 2);
//print ("Something in line of sight");
print (hit.collider.gameObject.name);
if (hit.collider.gameObject.name == "Player")
{
//print ("Player in line of sight");
InvokeRepeating ("Shooting", .001f, FireRateSeconds);
}
else
{
CancelInvoke ("Shooting");
}
}
}
void Shooting ()
{
GameObject TemporaryBulletHandler;
TemporaryBulletHandler = Instantiate (Bullet, BulletEmitter.transform.position, BulletEmitter.transform.rotation) as GameObject;
TemporaryBulletHandler.transform.Rotate(Vector3.forward);
Rigidbody TemporaryRigidbody;
TemporaryRigidbody = TemporaryBulletHandler.GetComponent ();
TemporaryRigidbody.AddForce (transform.forward * BulletForwardForce);
Destroy (TemporaryBulletHandler, 3.0f);
}
}
Thanks in advance :)
Pen
↧
Issue with starting/canceling invokes
Im having an issue with canceling/starting invokes in my update. I have a time "frenzyTimer" which sets a bool in another class in which will state what type of invoke should be running. The start invoke works fine. The first if statement in update works fine also. Its just the second if statement that doesnt work. The debugs are being called but the "FrenzySpawn" invoke is never cancelled and the "SpawnBall" invoke is never started. I even check to see if the invoke is not running, as isaid. The debugs are being called correctly. Help please. Thank you
public GameObject defaultBall,lifeBall,pointsBall,frenzyBall;
int invokeCount;
int spawnLocation;
float xPos;
float frenzyTimer;
int lifeBallChance;
int pointsBallChance;
int frenzyBallChance;
private void Start()
{
InvokeRepeating("SpawnBall", 0, 6); //Run the SpawnBall method every 6 seconds
invokeCount += 1; //Counts how many balls have been spawned
}
private void Update()
{
if (Ball.frenzyActive == true && !IsInvoking("FrenzySpawn")) //if frenzyActive is true and "FrenzySpawn" is not running
{
CancelInvoke("SpawnBall");
InvokeRepeating("FrenzySpawn", 0, 1);
Debug.Log("frenzy is active");
}
if (Ball.frenzyActive == false && !IsInvoking("SpawnBall")) //if frenzyActive is false and "SpawnBall" is not running
{
CancelInvoke("FrenzySpawn");
frenzyTimer = 0;
InvokeRepeating("SpawnBall", 0, 6);
Debug.Log("frenzy has been turned off");
}
Debug.Log("Frenzy time = " + frenzyTimer);
}
public void SpawnBall()
{
Debug.Log("Started spawn ball method");
lifeBallChance = Random.Range(1, 100);
pointsBallChance = Random.Range(1,100);
frenzyBallChance = Random.Range(1, 100);
if (lifeBallChance >= 90)
{
xPos = Random.Range(-8f, 8f);
Instantiate(lifeBall, new Vector3(xPos, 12, 14), Quaternion.identity);
}
else if (lifeBallChance <90 && pointsBallChance >= 80)
{
xPos = Random.Range(-8f, 8f);
Instantiate(pointsBall, new Vector3(xPos, 12, 14), Quaternion.identity);
}
else if (lifeBallChance <90 && pointsBallChance <80 && frenzyBallChance >95)
{
//spawn frenzy
}
else
{
xPos = Random.Range(-8f, 8f); //Gets a random X axis range between -8 & 8
Instantiate(defaultBall, new Vector3(xPos, 12, 14), Quaternion.identity); // spawns ball at xpos,12,-16 with default rotation
}
}
public void FrenzySpawn()
{
frenzyTimer += 1;
lifeBallChance = Random.Range(1, 100);
pointsBallChance = Random.Range(1, 100);
if (frenzyTimer <= 10)
{
if (lifeBallChance >= 90)
{
xPos = Random.Range(-8f, 8f);
Instantiate(lifeBall, new Vector3(xPos, 12, 14), Quaternion.identity);
}
else if (lifeBallChance < 90 && pointsBallChance >= 80)
{
xPos = Random.Range(-8f, 8f);
Instantiate(pointsBall, new Vector3(xPos, 12, 14), Quaternion.identity);
}
else
{
xPos = Random.Range(-8f, 8f); //Gets a random X axis range between -8 & 8
Instantiate(defaultBall, new Vector3(xPos, 12, 14), Quaternion.identity); // spawns ball at xpos,12,-16 with default rotation
}
}
if (frenzyTimer >10)
{
Ball.frenzyActive = false;
}
}
}
↧
↧
multiply Score on Collision not working? check my code plz
So what I'm trying to do here is when the player collide By " x2" object the score gets update +2 instead of +1 , I tried a lot of codes and I can't get anything to work, maybe its easy and I miss something, please check my code and guide me here
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class UIManager : MonoBehaviour{
public static bool gameOver;
public Text scoreText;
int score;
bool x2= false;
// Use this for initialization
void Start () {
gameOver = false;
score = 0;
InvokeRepeating ("scoreUpdate", 1.0f, 0.5f);
}
// Update is called once per frame
void Update () {
scoreText.text = "Score: " + score;
}
public void scoreUpdate() {
if (gameOver == false) {
if (x2 == false) {
score += 1;
}
if (x2 == true) {
score += 2;
}
}
}
public void gameover(){
gameOver = true;
}
void OnTriggerEnter2D (Collider2D col) {
if (col.gameObject.tag == "x2") {
Destroy (col.gameObject);
x2 = true;
float timer = 5.0f;
timer -= Time.deltaTime;
if (timer <= 0) {
x2 = false;
}
}
}
}
the scores only update +1 and never multiply when collision is happens.
↧
Can I increase gravity / fallspeed of instantiated prefabs over time?
Hello! I am working on a 2D color matching / catch game and I am trying to increase the gravity of my instantiated objects so the longer the game goes on, the faster they fall. Here is the code I am using to instantiate my prfabs:
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());
}
IEnumerator SpawnNewBox()
{
yield return new WaitForSeconds (1.75f);
while (!gameOver)
{
int i = Random.Range (0, boxList.Length);
Instantiate (boxList [i], 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);
}
public void GameOver()
{
gameOver = true;
}
}
I have tried using InvokeRepeating and AddForce in the start function and in an update function but with no luck. Any assistance / guidance is greatly appreciated!!
↧
How to cancel an Invoke from another script,How to Cancel an invoke from another script
So basically I'm trying to cancel an InvokeRepeating call from another script using this code:
void OnTriggerExit(Collider otherCollider) {
if (otherCollider.tag == "Player") {
CancelInvoke ("Approached");
But the cancel Invoke doesn't cancel it.
This is the invoke I am trying to cancel:
using UnityEngine;
using System.Collections;
public class EnemyAi : MonoBehaviour {
public Transform target;
public Transform myTransform;
Animator anim;
// Use this for initialization
void Start () {
anim = GetComponent ();
}
// Update is called once per frame
void Update () {
}
void Approaching () {
transform.LookAt (target);
transform.Translate (Vector3.forward * 1 * Time.deltaTime);
anim.SetInteger ("EnemyState", 1);
}
public void Attack () {
anim.SetInteger ("EnemyState", 2);
CancelInvoke ("Approached");
}
public void Approached () {
InvokeRepeating ("Approaching", 0.01f ,0.01f);
}
,
↧