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

InvokeRepeating continuously running twice

$
0
0
Running InvokeRepeating for some reason runs my function twice (I see the timer take values of 2, 4, 6, 8, and from the results i get it seems that my whole function gets called twice before printing out in Update In start I call InvokeRepeating("MatchUpdate", 1, 1.0f); which is: public void MatchUpdate() { test = timer; HPos = false; APos = false; HPS = HMor * 0.1f + HCoa * 0.2f + HDef * 0.2f + HMid * 0.5f; APS = AMor * 0.1f + ACoa * 0.2f + ADef * 0.2f + AMid * 0.5f; Possession = HPS / (HPS + APS) + Random.Range(-5, 5); BPos = Random.Range(-5, 5); if (BPos <= Possession) HPos = true; else APos = true; HPass = 0.25f * HCoa + 0.55f * HMid + 0.1f * Random.Range(0, 100) + 0.1f * HMor; APass = 0.25f * ACoa + 0.55f * AMid + 0.1f * Random.Range(0, 100) + 0.1f * AMor; HDefend = 0.3f * HCoa + 0.4f * HMid + 0.25f * HDef + 0.05f * Random.Range(0, 100); ADefend = 0.3f * ACoa + 0.4f * AMid + 0.25f * ADef + 0.05f * Random.Range(0, 100); HShoot = 0.6f * HAtk + 0.1f * HMor + 0.3f * Random.Range(0, 100); AShoot = 0.6f * AAtk + 0.1f * AMor + 0.3f * Random.Range(0, 100); HBlock = 0.7f * HDef + 0.2f * HCoa + 0.1f * HMor; ABlock = 0.7f * ADef + 0.2f * ACoa + 0.1f * AMor; if (HPos) { StatHPos++; Pass = HPass - ADefend; if (Pass <0) Pass = 0; if ((Pass + 10) >= Random.Range (0,100)) { StatHShoot++; if (HShoot - ABlock >= 0) { StatHGoals++; } } } else { StatAPos++; Pass = APass - HDefend; if (Pass <0) Pass = 0; if ((Pass + 10) >= Random.Range (0,100)) { StatAShoot++; if (AShoot - HBlock >= 0) { StatAGoals++; } } } timer++; } And I print out stats/results via another script, which get printed after every 2 calls of MatchUpdate. (Also I used the public variable "test" to monitor timer, and in the Inspector it still looks like it's getting called twice every time)

Problems with scripting and invokeRepeating

$
0
0
I want to start explaining that my english is not so good, so ill try me best. This is my problem: im making a "Hole in wall" game and im trying to Spawn 3 walls to test my script, i used invokerepeating for this task and invoking coroutines to create my wall and move it . i dont know if im making myself clear, but i hope u guys can undertand the idea. so... the problem is that after the first repeat my wall went to the original point and explode ( my wall was made by cubes order by a matrix), so when de second one comes,it explotes too. how can i fix this :/? this is my gameManager code. (C#) using UnityEngine; using UnityEngine; using System.Collections; using UnityEditor; using System.Collections.Generic; using System; public class GameManager : MonoBehaviour { public WallMaking Wall; float timer = 0f; // Use this for initialization public void Spawner() { timer += Time.deltaTime; //InvokeRepeating("Spawner()", 60f, 3f); Debug.Log("SPAWNEA CTM!"); Debug.Log(timer); StartCoroutine(Wall.WallMaker()); Vector3 Source = new Vector3(661.49f, 0.2f, 3.52f); Vector3 Target = new Vector3(661.49f, 0.2f, -4.87f); StartCoroutine(Wall.WallsMovement(Source, Target, 5f)); Debug.Log("hola"); Debug.Log(timer); } void Start() { Debug.Log("A VER"); InvokeRepeating("Spawner", 1f, 5f); Debug.Log("SE REPITE"); } //float timer = 0f; } and this is my wallmaking code: using UnityEngine; using System.Collections; using UnityEditor; using System.Collections.Generic; // C# public class WallMaking : MonoBehaviour { int[,] mat ={ {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1}, }; int[,] mat2 ={ {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,0,0,1,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1}, }; int[,] mat3 ={ {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1}, }; int[,] matO; List wallList = new List(); public IEnumerator WallMaker() { wallList.Add(mat); wallList.Add(mat2); wallList.Add(mat3); System.Random rnd = new System.Random(); matO = wallList[rnd.Next(wallList.Count)]; float cubesizeX = 0; float cubesizeY = 0; for (int y = 0; y < 11; y++) { for (int x = 0; x < 11; x++) { if (matO[y, x] == 1) { GameObject Brick = GameObject.CreatePrimitive(PrimitiveType.Cube); Brick.transform.localScale = new Vector3(transform.localScale.x, transform.localScale.y, transform.localScale.z); Brick.AddComponent().useGravity = false; Vector3 newPos = new Vector3((transform.position.x) + cubesizeX, (transform.position.y) + cubesizeY, transform.position.z); Brick.transform.position = newPos; Brick.transform.parent = GameObject.Find("MainWall").transform; } cubesizeX = cubesizeX + 0.3F; } cubesizeX = 0; cubesizeY = cubesizeY + 0.3F; } Debug.Log("MAKING A WALL"); yield return null; } public IEnumerator WallsMovement(Vector3 source, Vector3 target, float overTime) { float startTime = Time.time; while (Time.time < startTime + overTime) { Debug.Log("TIEMPO DE MOVERTE"); Debug.Log(startTime + overTime); transform.position = Vector3.Lerp(source, target, (Time.time - startTime) / overTime); yield return null; } transform.position = target; } //void Update() { //KinectManager manager = KinectManager.Instance; //uint playerID = manager != null ? manager.GetPlayer1ID() : 0; //if (playerID > 0) { // transform.Translate (-Vector3.forward* 2.0f * Time.deltaTime, Space.Self); //} // Debug.Log("MUEVETE"); //yield return null; // } } hope u guys can helpme !

Using invokerepeatng in update

$
0
0
I'm working on a version of [Conway's Game of Life][1] in Unity, and I've got the code working for checking cells and stepping through the next generation. However, I'm running into problems using update: void Update() { bool spaceKey = Input.GetKey(KeyCode.Space); if(spaceKey && _start == false) { _start = true; }else if(spaceKey && _start) { _start = false; } if (_start) { InvokeRepeating("GoThroughGenerations", .5f, .5f); } } private void GoThroughGenerations() { for (int i = 0; i < numCols; i++) { for (int j = 0; j < numRows; j++) { CheckNeighbors(i, j); } } NextGeneration(); } Once I hit space, it looks fairly well, but there is some jumpiness. Once I hit the space bar again, it runs the function every frame. My goal is to run through the functions, display the next generation on the grid, then wait a short break before going to the next generation. What's the best way of doing this, or is InvokeRepeating the best way of doing this? [1]: https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life

InvokeRepeating

$
0
0
Hi I'm using c# and I'm currently making a perk script and when the player picks up this perk the players ammo increases every 10 seconds. The perk is a game object as well.However my code doesn't seem to be right as when I play through the game and error comes up saying ![alt text][1] [1]: /storage/temp/59838-capture23.png Here is the script I have used; public class PerkScript : MonoBehaviour { public GameObject ammoPerk; float ammoUpTime = 10f; // Use this for initialization void Start () { InvokeRepeating("TopUpAmmo", ammoUpTime, ammoUpTime); } // Update is called once per frame void Update () { } void OnControllerColliderHit(ControllerColliderHit hit) { PlayerScript playerScript = GetComponent(); if (hit.gameObject.tag == "AmmoPerk") { playerScript.reserveAmmo += 10; Destroy(hit.gameObject); } } } Thanks for the help if any and would be much appreciated.

Constantly Targeting with an InvokeRepeating and Random Targeting

$
0
0
Hi, I have a script which in theory is fine, but there are lots of things that don't work to plan (not syntax errors, the script is fine). It is in C#. The main issue is that I want my object to target the target and follow it for 5 seconds until it resets, but it constantly follows the player, does anybody have any ideas why it would do this and how to stop it? The 2nd issue is that tr_player (the transform variable) always sets itself to my 5th target, so if anyone has any ideas about that it would be very helpful. This is my script: public Transform Bird; public Transform tr_Player; public float f_MoveSpeed = 25.0f, f_RotSpeed = 1000.0f; void Start () { tr_Player = GameObject.FindGameObjectWithTag ("Target").transform; InvokeRepeating("Reset",5, 5); } void Update () { transform.position += transform.forward * f_MoveSpeed * Time.deltaTime; } void Reset() { transform.position = Bird.position; tr_Player = GameObject.FindGameObjectWithTag ("Target").transform; transform.LookAt(tr_Player); } } Probably just a noob error but if anyone could help me with those two errors it would be really helpful!

Spawn prefab at a random time C#

$
0
0
Hi Everyone, I have written code to spawn random objects out of my resources folder. after every second using invoke repeating. This all works but I am now trying to spawn these objects at a random time between 1 and 3 seconds. The code I have written spawn one object and then does not spawn any more. Please can someone help me figure out how to use a random time that works - maybe Invoke Repeating is not the best option? Here is the code I have tried so far using UnityEngine; using System.Collections; public class spawncar : MonoBehaviour { public int totalNumberOfItemsInAvailableCars = 3; public int mint; public int maxt; public int calculatedtime; void Start () { InvokeRepeating("spawncars", 2,calculatedtime); Debug.Log ("Launched"); } void spawncars(){ int randomNum = Random.Range (0, totalNumberOfItemsInAvailableCars); Object objTemp = Resources.Load ("cars/" + randomNum); Instantiate (objTemp); } void Update(){ calculatedtime = Random.Range (mint, maxt); } }

My new invoke does not appear in the position I want.

$
0
0
public class elcajon : MonoBehaviour { public GameObject Player; // Use this for initialization void Start () { InvokeRepeating ("BlockDown", 5, 5); } // Update is called once per frame void Update () { } void BlockDown () { Instantiate(Player,new Vector3(2.5f,6f,0), Quaternion.identity ); } }

InvokeRepeating() Does Not Use Repeat Rate?

$
0
0
I'm trying to call InvokeRepeating() in one of my classes: public class TerrainPlayer : MonoBehaviour { void Update() { // refresh the terrains height so that terrain (and tree) collision happen correctly // use "InvokeRepeating" to have it refresh over time, and not every frame InvokeRepeating("RefreshCollider", 10.0f, 10.0f); } void RefreshCollider() { Terrain.activeTerrain.RefreshTerrainCollider(); } } public static class TerrainExtensions { public static void RefreshTerrainCollider(this Terrain terrain) { Debug.Log("Refreshing the Terrain's height at: " + Time.time); // Refresh the terrain's heights, ensuring the TerrainCollider remains accurate float[,] heights = terrain.terrainData.GetHeights(0, 0, 0, 0); terrain.terrainData.SetHeights(0, 0, heights); } } I have set it to invoke the method (for testing purposes) 10 seconds from now and then again every 10 seconds. It waits the 10 seconds to perform the first invocation, but then invokes the method every frame that follows. Invoking that method is extremely costly which is why I only want it done every so many seconds, and not every update, hence InvokeRepeating()... I've tried many other values like: 1, 1.0f, 2f, 2.2f etc. but the same thing happens. Did I do something wrong? Is there a new or different method that will do the same thing? What will fix it so I can call the method once every x seconds? Thanks!

Prefabs not instantiating when first run

$
0
0
So I have a script that's supposed to instantiate a bunch of objects randomly chosen from an array depending on a value taken from another array, all using InvokeRepeating. It worked when I was testing it out but when I made a build of the game the objects weren't being instantiated. I also noticed that when I closed unity and opened it again I got the same problem when I ran it the first time, but when I stopped it and ran it again it worked fine. I'm not getting any errors or anything so I'm not sure whats going on. Here's the code that's supposed to instantiate the objects. void Start() { InitiateSpawn(); } // Update is called once per frame void Update () { Debug.Log("Time is " + Time.realtimeSinceStartup); } void startTheMusic() { theMusic.enabled = true; } void InitiateSpawn() { InvokeRepeating("arrowSpawning", 0, 1 / 1.916667f); } void arrowSpawning() { Debug.Log(arrowCounter); //spawns arrows based on the sample value if (sampleSelection[arrowCounter] < -0.25 && sampleSelection[arrowCounter] > -0.5) { Instantiate(arrows[1], new Vector2(transform.position.x, transform.position.y), Quaternion.identity); } if (sampleSelection[arrowCounter] < -0 && sampleSelection[arrowCounter] > -0.25) { Instantiate(arrows[0], new Vector2(transform.position.x, transform.position.y), Quaternion.identity); } if (sampleSelection[arrowCounter] < 0.25 && sampleSelection[arrowCounter] > 0) { Instantiate(arrows[3], new Vector2(transform.position.x, transform.position.y), Quaternion.identity); } if (sampleSelection[arrowCounter] < 0.5 && sampleSelection[arrowCounter] > 0.25) { Instantiate(arrows[2], new Vector2(transform.position.x, transform.position.y), Quaternion.identity); } arrowCounter++; }

Invoke Repeating Problem

$
0
0
I'm new to the whole invoke repeating part of code so naturally having issues with this. I'm trying to get it so that if I have my repeat toggle "ON" then after a specified time frame the message will be repeated. But I keep getting this: ![Error In Console][1] [1]: /storage/temp/63122-screen-shot-2016-02-02-at-93104-am.png using UnityEngine; using System.Collections; using System.Text.RegularExpressions; using UnityEngine.UI; public class MorseCodePlayer : MonoBehaviour { public bool iSOn = false; public InputField inputFieldMCode; public Text morseCodeDisplayText; public AudioClip dotSound; public AudioClip dashSound; public float spaceDelay; public float letterDelay; // International Morse Code Alphabet private string[] alphabet = //A B C D E F G {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", //H I J K L M N "....", "..", ".---", "-.-", ".-..", "--", "-.", //O P Q R S T U "---", ".--.", "--.-", ".-.", "...", "-", "..-", //V W X Y Z "...-", ".--", "-..-", "-.--", "--..", //0 1 2 3 4 "-----", ".----", "..---", "...--", "....-", //5 6 7 8 9 ".....", "-....", "--...", "---..", "----."}; // Use this for initialization void Start () { //morseCodeDisplayText = GameObject.Find ("MorseCodeDisplayText").GetComponent (); inputFieldMCode = GameObject.Find ("InputField").GetComponent (); // H E L L O W O R L D //.... . .-.. .-.. --- .-- --- .-. .-.. -.. //PlayMorseCodeMessage("Hello World."); PlayMorseCodeMessage (""); } public void MorseCodeField(string inputFieldString){ morseCodeDisplayText.text = inputFieldString; } public void RepeatMessage (){ Debug.Log ("Checking if Bool is On"); if (iSOn = true) { InvokeRepeating ("repeat", 15f, 1f); Debug.Log ("I will Invoke Repeat"); } Debug.Log ("Confirming Bool Is On!"); } //Repeat Message Being Sent after "X" time has passed. void repeat (string message){ Debug.Log ("I Will Submit Text"); StartCoroutine("_PlayMorseCodeMessage", message); //I thought this would just restart the message send Coroutine? submitText (); Debug.Log ("I HAVE Submited Text"); } public void readButton (string c){ inputFieldMCode.text += c; } string messageToSend; public void submitText(){ messageToSend = inputFieldMCode.text; } public void PlayMorseCodeMessage(string message) { StartCoroutine("_PlayMorseCodeMessage", message); } private IEnumerator _PlayMorseCodeMessage(string message) { // Remove all characters that are not supported by Morse code... Regex regex = new Regex("[^A-z0-9 ]"); message = regex.Replace(message.ToUpper(), ""); // Convert the message into Morse code audio... foreach(char letter in message) { if (letter == ' ') yield return new WaitForSeconds(spaceDelay); else { int index = letter - 'A'; if (index < 0) index = letter - '0' + 26; string letterCode = alphabet[index]; foreach(char bit in letterCode) { // Dot or Dash? AudioClip sound = dotSound; if (bit == '-') sound = dashSound; // Play the audio clip and wait for it to end before playing the next one. GetComponent().PlayOneShot(sound); yield return new WaitForSeconds(sound.length + letterDelay); } } } } }

Make a gameobject spawn before enemies spawn? (C#)

$
0
0
Hello! I'm developing a 2D mobile game and I have a little problem. I have created a spawn system, that spawns bouncing balls at a random location inside a rectangle. I'm now trying to create a spawn system for another gameobject, this gameobject is meant to show where the bouncing ball will spawn. It'll only show up for a second just so the player can identify and highlight that "Ahhh an enemy ball will spawn here". The Gameobject is called "ShowEnemySpawn" and I instantiate it in the same function that spawns out the enemy balls using the same position, I also use InvokeRepeating to make the bouncing balls spawn out every 2 seconds. How do I spawn the "ShowEnemySpawn" Gameobject for 1 sec before the Bouncing enemy ball spawn? I've been trying to search for a solution, but has been unable to find a one. So I'm really grateful for any help I can get! Here is the code! using UnityEngine; using System.Collections; public class EnemySpawn : MonoBehaviour { // EnemyPrefab public GameObject EnemyBouncingPrefab; //Show where spawn is prefab public GameObject ShowEnemySpawn; // Borders public Transform borderTop; public Transform borderBottom; public Transform borderLeft; public Transform borderRight; void Start () { // Spawn boucning enemies every 2 seconds, starting in 3 InvokeRepeating("SpawnBouncingEnemy", 3, 2); } // Spawn a Bouncing enemy void SpawnBouncingEnemy() { // x position between left & right border int x = (int)Random.Range (borderLeft.position.x, borderRight.position.x); // y position between top & bottom border int y = (int)Random.Range (borderBottom.position.y, borderTop.position.y); // Sets the prefab where an enemy will spawn Instantiate (ShowEnemySpawn, new Vector2 (x, y), Quaternion.identity); // Instantiate the power up at (x, y) Instantiate (EnemyBouncingPrefab, new Vector2 (x, y), Quaternion.identity); // default rotation } }

I need to Stop and Restart a Co-Routine at anytime

$
0
0
My problem is that co-routines are overlapping eachother. I have even called StopAllCoroutines right before starting a new one, yet they still overlap. How can I ensure that only a single co-routine exists at one time? Can anyone explain why they are overlapping even though I'm calling StopAllCoroutines before starting a new one? void OnEnable() { if (!isRunning) { StopAllCoroutines (); StartCoroutine (levelManagement ()); } } void Update() { if (LoseGame.loseGame == true) { isRunning = false; this.enabled = false; } } IEnumerator levelManagement() { isRunning = true; while (isRunning) { //Level 1 InvokeRepeating ("SpawnRandomCubes", 0.25f, 0.25f); yield return new WaitForSeconds (10f); CancelInvoke ("SpawnRandomCubes"); InvokeRepeating ("SpawnSingleEntries", 1.5f, 1.5f); yield return new WaitForSeconds (4.5f); CancelInvoke ("SpawnSingleEntries"); InvokeRepeating ("SpawnRandomCubes", 0.25f, 0.25f); yield return new WaitForSeconds (10f); CancelInvoke ("SpawnRandomCubes"); //Level 2 StartCoroutine(SpawnZigZag(2)); yield return new WaitForSeconds (10f); StopCoroutine (SpawnZigZag (2)); InvokeRepeating ("SpawnRandomCubes", 0.2f, 0.2f); yield return new WaitForSeconds (15f); CancelInvoke ("SpawnRandomCubes"); } yield break; }

InvokeRepeating not working

$
0
0
Hi guys, So I'm trying to make the speed of my shuriken increase by 2 after 30 seconds, and then every 30 seconds after that. From what I read in the documentation, this should be how it's done? private Rigidbody2D rb2d; public float speed = 10f; public GameObject DownShuriken; public static int livess = 2; void Start () { rb2d = GetComponent (); } void Update () { rb2d.AddForce(Vector2.down*speed); InvokeRepeating ("IncreaseSpeed", 30, 30f); } void SpawnShurikenDown() { Vector3 RandomSpawn = new Vector3 (Random.Range (-9.1F, 9.1F), Random.Range (5.04F, 5.04F),1F); Instantiate (DownShuriken, RandomSpawn, Quaternion.identity); } void OnTriggerExit2D(Collider2D other) { if(other.gameObject.CompareTag ("BottomBackground")) { SpawnShurikenDown (); Destroy (DownShuriken); } } void IncreaseSpeed () { speed = speed + 2f; } } After 30 seconds, the speed of the shuriken does not change. A Debug.LogError (speed) does nothing inside the function IncreaseSpeed when put beneath the line where I change the speed.

Adding a point to variable every second doesn't work

$
0
0
public static int pscore = 0; void Start() { InvokeRepeating("AddToMoney",1, 1); } void AddToMoney () { pscore++; } Why does it add 2 points to my integer every second instead of 1? Does it have anything to do with pscore being static? And if so, how can I fix it or how can I transfer pscore to another script without using static?

How to change the bullet fire rate in C#?

$
0
0
I tried use "Invoke" to make it, but it will repeat shooting every frame. Not every fixed second. I wants to make it shoot in every 0.5 second. So how can I realize it?

Invoke Repeating Issue

$
0
0
I am trying to change up my enemies slightly when the user surpasses a certain score. Right now I have an invoke repeating function that starts when the game starts. This works fine, but when the player reaches 50,000 points I wanted to add some extra effects to the enemies. The code I have does not work and I understand why (the invoke repeating is constantly being executed due to being in the update function). I really want to incorporate this in my game, but am unsure on what to do. Here's my code: using UnityEngine; using System.Collections; public class GloveSpawner : MonoBehaviour { public Transform []spawnPoints; public float spawnTime = 2f; public GameObject [] Gloves; public GameObject[] FireGloves; void Start(){ InvokeRepeating ("SpawnGloves", spawnTime, spawnTime); } void Update(){ /*if (ScoreManager.scoreCount >= 50000) { CancelInvoke ("SpawnGloves"); InvokeRepeating ("SpawnFireGloves", spawnTime, spawnTime); }*/ } void SpawnGloves(){ int spawnIndex = Random.Range (0, spawnPoints.Length); int objectIndex = Random.Range (0, Gloves.Length); Instantiate (Gloves [objectIndex], spawnPoints [spawnIndex].position, spawnPoints [spawnIndex].rotation ); } void SpawnFireGloves(){ int spawnIndex = Random.Range (0, spawnPoints.Length); int objectIndex = Random.Range (0, FireGloves .Length); Instantiate (FireGloves [objectIndex], spawnPoints [spawnIndex].position, spawnPoints [spawnIndex].rotation); } }

Invoke () Working like InvokeRepeating ()

$
0
0
I am calling this invoke function after my player dies. I want him to respawn with a delay. It does get called after a five second delay, but then it gets called for five seconds as well and my player is stuck in his position for five seconds. Any help is greatly appreciated. :) using UnityEngine; using System.Collections; public class Player_Death : MonoBehaviour { private GameObject spawnPoint; public Vector3 startPos; public Transform armature; public GameObject lowestLevel; public bool dead = false; private bool callRespawn; public GameObject center; // Use this for initialization void Start () { spawnPoint = GameObject.Find ("SpawnPoint"); startPos = spawnPoint.transform.position; startPos.y += 1f; if (armature != null) { foreach (Transform child in armature) { child.position = startPos; } } callRespawn = true; } // Update is called once per frame void Update () { if (center.transform.position.y <= lowestLevel.transform.position.y) { dead = true; } if (dead == true && armature != null) { Invoke ("Respawn", 5f); } else if (dead == true && armature == null) { transform.position = startPos; transform.root.GetComponent ().health = 100f; dead = false; } print (dead); } private void Respawn () { print ("here " + 1 + Time.time); foreach (Transform child in armature) { child.GetComponent ().velocity = Vector3.zero; child.position = startPos; child.GetComponent ().isKinematic = false; } transform.root.GetComponent ().health = 100f; dead = false; } }

Simple timer using InvokeRepeating

$
0
0
I have tried making a simple timer script that uses Invoke, and more recently, InvokeRepeating. It seems simple enough, but I'm having an issue where it will blast through the first 10 seconds, calling Tick() in rapid succession. Here is my current code. public class TimerBehavior : MonoBehaviour { public delegate void TickDelegate(int secondsRemaining); public TickDelegate OnTick; public delegate void CompleteDelegate(); public CompleteDelegate OnComplete; int secondsRemaining = 0; public void Go(int seconds){ secondsRemaining = seconds; InvokeRepeating("Tick", 0, 1f); } void Tick(){ if (OnTick != null) { OnTick (secondsRemaining); } if (secondsRemaining > 0) { secondsRemaining--; } if(secondsRemaining == 0){ if(OnComplete != null){ OnComplete(); } Stop (); } } public void Stop(){ CancelInvoke ("Tick"); } } For simplicity-sake, ignore the fact that there will be issues if Go() is called while the timer is already ticking. Is there anything blatantly wrong with this code?

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


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