Quantcast
Channel: Questions in topic: "invokerepeating"
Viewing all 220 articles
Browse latest View live

Why aren't Coroutines working for me?

$
0
0
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

$
0
0
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

$
0
0
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

$
0
0
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

$
0
0
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

$
0
0
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

$
0
0
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

$
0
0
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?

$
0
0
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

$
0
0
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); } ,

Calling CancelInvoke() ?

$
0
0
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 [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); 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!!!

IndexOutOfRangeException: Array index is out of range

$
0
0
IndexOutOfRangeException: Array index is out of range, it's my problem with this script at 37th line (GameObject Newaster = Instantiate (aster[spawnObject], spawnPoints [spawnIndex].position, spawnPoints [spawnIndex].rotation) as GameObject;): using System.Collections; using UnityEngine; using UnityEngine.Networking; using System.Collections.Generic; public class Asteroid : NetworkBehaviour { public float timeTospawn = 0.5f; public Transform[] spawnPoints; public GameObject[] aster; public List possibleSpawns = new List(); // Use this for initialization void Start() { //fill possible spawn for (int i = 0;i().mySpawnPoint = possibleSpawns[spawnIndex]; possibleSpawns.RemoveAt(spawnIndex); } }

InvokeReapting() Repeat rate not updating

$
0
0
When I shoot I use InvokeRepeating to continuously shoot until I let go of space. In game there is a powerup which decreases this repeat rate but I need to stop shooting then star shooting for it to actually make an effect and when the repeat rate variable in the code is set back to normal it doesn't take effect until I stop shooting and start shooting again. How would I fix this so that it updates without me having to stop shooting and start shooting agian?

[Solved] Is Invoke Repeating Frame Independent??

$
0
0
Hello everybody, im have the same problem since weeks: Getting my player movement frame independent! I cant do it in Fixed Update because it will move Jittering. Im using a Character Controller. So i create a custom Method with Invoke Repeating. I think its frame idependend but the problem is that at 1000 fps the player has less gravity then at 60. How is that possible!!! Heres my custum method: void Awake() { remainingHealth = Health; remainingEnergy = Energy; remainingArmor = Armor; canJump = true; InvokeRepeating("TimedUpdate", 0, 0.1f); InvokeRepeating("Move", 0, 0.001f); //Here it is calling my move method every 0.001 seconds. } //Thats my move method wich is called every 0.001 seconds. Everything is time base how can it be that at 200 fps it can jump heigher than at 60. This problem is makeing me crazy!!! void Move() { if (!isDrone) { if (cc.isGrounded && canControl) { move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); move = transform.TransformDirection(move); remainingEnergy += energyIncrease; move *= walkSpeed; movementState = 0; movementInfo.text = "Movement state: Standing"; //if the player is walking or crouching it does not cost any energy if (move.x != 0 && move.z != 0) { movementState = 1; step = 0.5f; movementInfo.text = "Movement state: Walking"; } if (Input.GetButton("Sprint") && canRun && remainingEnergy > sprintEnergyCost) { move *= runSpeed; remainingEnergy -= sprintEnergyCost; movementState = 2; step = 0.3f; movementInfo.text = "Movement state: Sprinting"; } if (Input.GetButtonDown("Jump") && canJump && remainingEnergy > jumpEnergyCost) { move.y += jumpSpeed; remainingEnergy -= jumpEnergyCost; movementState = 3; footstepsAudio.clip = Jump; footstepsAudio.Play(); movementInfo.text = "Movement state: Jumping"; } if (Input.GetButton("Crouch")) { cc.height = 1f; move /= crouchSpeed; movementState = 4; step = 0.8f; canRun = false; movementInfo.text = "Movement state: Crouching"; } else { cc.height = 2; canRun = true; } } } move.y -= gravity; cc.Move(move); } Thanks in advance and please help!!! Regards, T

How i can make a function call and then after 15 sec another function call during this function call the first one stops.And this process keep repeating again and again.

$
0
0
I have a 2D game. I am in a problem. My game has three levels. Actually i have to cars. one is white other is yellow. And there are two types of incoming circles white and yellow. and currently my game is running perfectly. In level one, when yellow car collides with yellow it increases score.same for white car when it collide with white circle score increases. In level 2 everything is same except the factor that cars have to collect opposite color circles. Now in level 3 what i want is that when it starts the cars have to collect same color circles like in level one and after 15 sec cars have to collect opposite color circles like in level 2. and after 15 sec again cars have to collect same color circles like level one.. And this all keeps repeating. really need help its urgent guys. Thank you in advance. This code is for level 1 void OnTriggerEnter2D(Collider2D other){ if (other.CompareTag ("white") && car == "white") { Destroy (other.gameObject); SoundManager.instance.PlaySingle (circle); count = count + 1; SetCountText (); } if (other.CompareTag ("Yellow") && car == "white") { Application.LoadLevel (2); } if (other.CompareTag ("Yellow") && car == "yellow") { Destroy (other.gameObject); SoundManager.instance.PlaySingle (circle); count = count + 1; SetCountText (); } if (other.CompareTag ("white") && car == "yellow") { Application.LoadLevel (2); } } This is for Level 2 void OnTriggerEnter2D(Collider2D other){ if (other.CompareTag ("Yellow") && car == "white") { Destroy (other.gameObject); SoundManager.instance.PlaySingle (circle); count = count + 1; SetCountText (); } if (other.CompareTag ("white") && car == "white") { Application.LoadLevel (2); } if (other.CompareTag ("white") && car == "yellow") { Destroy (other.gameObject); SoundManager.instance.PlaySingle (circle); count = count + 1; SetCountText (); } if (other.CompareTag ("Yellow") && car == "yellow") { Application.LoadLevel (2); } }

SNAKE - How to change InvokeRepeating rate?

$
0
0
Hi this is the start function attached to my snake: void Start() { InvokeRepeating("Move", 0.3f, repeatRate); score = 0; SetScoreText(); textYouLose.text = ""; } i wish to change the repeat rate every 5 points (or every time the snake eats 5 pieces of food) I've tought something like if(score % 5 == 0) { repeatRate /= 2; } but it doen't work! Any idea? thanks

InvokeRepeating VS Coroutines [Performance]

$
0
0
**Hello everyone.** I was wondering, what is better to use InvokeRepeating or Coroutines? I want to optimize my scripts and instead of calling stuff every frame per seconds inside the Update() function only call the specific function for example every 0.25f seconds. So I decided to use either InvokeRepeating or Coroutines. But I don't know what is better in terms of performance. I wrote couple of simple script. Which example is more optimized? **InvokeRepeating:** using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraReposition : MonoBehaviour { [SerializeField] private Camera[] cameras; [SerializeField] private Transform pos; public bool forceRePosition; void Start () { InvokeRepeating("ForceRePosition", 0f, 0.2f); } void ForceRePosition () { if (!forceRePosition) return; cameras[0].gameObject.transform.position = pos.position; cameras[1].gameObject.transform.position = pos.position; } } **Coroutines:** using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraReposition : MonoBehaviour { [SerializeField] private Camera[] cameras; [SerializeField] private Transform pos; [SerializeField] private float WaitTime = 0.2f; public bool forceRePosition; void Start () { StartCoroutine(ForceRePosition(WaitTime)); } IEnumerator ForceRePosition (float waitTime) { while (forceRePosition) { yield return new WaitForSeconds(waitTime); RePosition(); } } public void RePosition () { cameras[0].gameObject.transform.position = pos.position; cameras[1].gameObject.transform.position = pos.position; } }

I have no idea why this isn't working

$
0
0
So i have got this script here and it is saving and loading data fine, thats not the problem but the realAnts value is not changing and i have no idea why, as im pretty sure all the things start repeating when level 2 loads, and there is definitely a gameManager object in the scene so anyone got an ideas why this isn't working; using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; using UnityEngine; public class GameManager : MonoBehaviour { public int ants; public int queens; public int coins; [SerializeField] private float realAnts; private float nl3; private const float BR = 1 / 60; private float multiplier; private int currentSaveGame; private GameObject inventory, shop, menu; private MenuButtons[] menuButtons; private CurrencyDisplays[] currencyDisplays; private void Awake() { DontDestroyOnLoad(gameObject); nl3 = Mathf.Log(3f); } private void CalculateBonus() { float _nlAnts = Mathf.Log(ants); float _power = _nlAnts / nl3; float _firstMultiplier = Mathf.Pow(1.5f, _power); multiplier = _firstMultiplier * queens; } private void GiveAnts() { realAnts += BR * multiplier; ants = Mathf.RoundToInt(realAnts); foreach (CurrencyDisplays _currencyDisplay in currencyDisplays) { _currencyDisplay.SetText(); } } private void OnLevelWasLoaded(int level) { if (level == 2) { InvokeRepeating("CalculateBonus", 0f, 60f); InvokeRepeating("GiveAnts", 0f, 1f); InvokeRepeating("Save", 5f, 5f); menuButtons = GameObject.FindObjectsOfType(); foreach (MenuButtons _menuButton in menuButtons) { _menuButton.Setup(); } currencyDisplays = GameObject.FindObjectsOfType(); foreach (CurrencyDisplays _currencyDisplay in currencyDisplays) { _currencyDisplay.Setup(); } if (menu == null) { menu = GameObject.FindGameObjectWithTag("Menu"); shop = GameObject.FindGameObjectWithTag("Shop"); inventory = GameObject.FindGameObjectWithTag("Inventory"); } shop.SetActive(false); inventory.SetActive(false); menu.SetActive(true); } if (level == 1) { CancelInvoke(); } } public void SetStuff() { ants += 10; queens += 10; coins += 10; StartSave(ants, queens, coins, realAnts); } public void StartSave(int _ants, int _queens, int _coins, float _realAnts) { ants = _ants; queens = _queens; coins = _coins; realAnts = _ants; Save(); } public void ExitToMenu() { CancelInvoke(); Save(); } private void OnApplicationQuit() { CancelInvoke(); Save(); } public void Save() { Debug.Log("Saving Data"); BinaryFormatter _bf = new BinaryFormatter(); FileStream _file = File.Create(Application.persistentDataPath + "/SaveGame" + currentSaveGame); PlayerData _data = new PlayerData(); _data.coins = coins; _data.queens = queens; _data.ants = ants; _data.realAnts = realAnts; _bf.Serialize(_file, _data); _file.Close(); } public void Load(int _saveGame) { currentSaveGame = _saveGame; Debug.Log("Loading Data"); if (File.Exists(Application.persistentDataPath + "/SaveGame" + _saveGame)) { BinaryFormatter _bf = new BinaryFormatter(); FileStream _file = File.Open(Application.persistentDataPath + "/SaveGame" + _saveGame, FileMode.Open); PlayerData _data = (PlayerData)_bf.Deserialize(_file); _file.Close(); coins = _data.coins; ants = _data.ants; queens = _data.queens; realAnts = _data.realAnts; print(coins + " " + ants + " " + queens); } else { Debug.Log("File Does Not Exist"); coins = 650; queens = 1; ants = 1; realAnts = 1; } } } [Serializable] class PlayerData { public int ants; public int coins; public int queens; public float realAnts; }

InvokeRepeating gets crazy when Time.timeScale is increased

$
0
0
I have a simple 2D game in Unity 2017.2 where the player has to jump obstacles, and to raise difficulty I want to increase the speed of the game, so **i am using a InvokeRepeating method to increase Time.timeScale peridiocally**, but when I do that, the 1st time the InvokeRepeating method starts right, but **after modifiying the timeScale, the following times that the the InvokeRepeating method is executed it goes much faster in each execution**. It is like it is not interpreting that 1 second is actually 1 second anymore, because the timeScale has been modify. I hope I explain myself right. This is the code simplyfied: ` void Update() { InvokeRepeating("GameTimeScale", 6f, 6f); } void GameTimeScale(){ Time.timeScale += 0.25f; Debug.Log ("Ritmo incremental. TimeScale: " + Time.timeScale.ToString ()); } Any idea? I did something wrong? I am kind of new with unity

InvokeRepeating not working in unity with .Net 4.6

$
0
0
I attached the below script to the camera using System.Collections; using System.Collections.Generic; using UnityEngine; public class Sample : MonoBehaviour { int i=0; void Start () { Debug.Log("This is printed immediately"); Debug.Log("Called invoke repating "); InvokeRepeating("test", 0.0f, 0.5f); } void test() { i++; Debug.Log("Called invoke repating "+i); } void Update () { } } This is what I get when I run the game (it stops and test doesn't get invoked repeatedly): This is printed immediately UnityEngine.Debug:Log(Object) Sample:Start() (at Assets/Sample.cs:27) Called invoke repating UnityEngine.Debug:Log(Object) Sample:Start() (at Assets/Sample.cs:28) Called invoke repating 1 UnityEngine.Debug:Log(Object) Sample:test() (at Assets/Sample.cs:36) Does anyone have a clue what is going on... I can't seem to spot any mistake here Any help ? [Screenshot][1] I have 2017.2.0f3 version on mac os and the screenshot is attached [1]: https://i.stack.imgur.com/AWh7i.jpg
Viewing all 220 articles
Browse latest View live


Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>