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

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; }

Improving script which Spawns enemies up to a required number

$
0
0
This script I have written spawns fish up to a required number and upholds that number of fish in the scene, respawning more up to the number when fish get destroyed. Could anyone offer some improvements on it? How can I make it run faster? using UnityEngine; using System.Collections; public class randomFish : MonoBehaviour { public GameObject[] fish; // this is where all the spawned fish are held public int maxAmountOfFish; // wanted maximum amount of fish in scene private int amount; // amount of fish in GameObject[] fish private Vector3 spawnPoint; // spawn point of fish private int randomFishNumber; // number of prefab selected to be cloned at random public GameObject fishClone; void Update () { GameObject[] fish = GameObject.FindGameObjectsWithTag ("fish"); amount = fish.Length; // the amount of fish in the scene is the length of the array called "fish" if (amount != maxAmountOfFish) { InvokeRepeating ("Spawn", 1, 60f); } } void Spawn () { spawnPoint.x = Random.Range (-2.5f, -5.0f); // spawn points to spawn from spawnPoint.y = Random.Range (-0.8f, -0.5f); spawnPoint.z = Random.Range (-5.0f, 5.0f); randomFishNumber = Random.Range (1, 6); // random fish 1-5 (6 excluded) fishClone = Resources.Load ("FishPrefabs/SALMON" + randomFishNumber) as GameObject; Debug.Log (fishClone); fishClone = Instantiate (fishClone, spawnPoint, Quaternion.identity) as GameObject; fishClone.tag = "fish"; CancelInvoke(); } }

How to run InvokeRepeating for x amount of seconds?

$
0
0
So in my code I currently have this: public GameObject enemyPrefab; Vector3 position = new Vector3(81.5f, 1.859728f, 4.802853f); // Use this for initialization void Start() { InvokeRepeating("SpawnEnemy", 0.0f, 1f); } // Update is called once per frame void Update () { } void SpawnEnemy() { Instantiate(enemyPrefab, position, Quaternion.identity); } What I need is for InvokeRepeating to only run a certain number of times. For example, having an integer that represents the amount of times I need it to run.

Prevent object from spawning at a spawn point twice in a row?

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

HOW TO INSTANTIATE IMAGE INSIDE CANVAS?

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

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

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

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

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

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

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

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

$
0
0
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.
Viewing all 220 articles
Browse latest View live


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