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

Custom fixed update cycle?

$
0
0
I want to call an event every X seconds where X is variable. I've looked into InvokeRepeating but it seems like I can't modify the rate after calling the method. I think the best way would be to use a repeating coroutine. Does StartCoroutine_Auto do this? I'm a bit confused as to how it works. If anyone can show me an example, I'd really appreciate it. Thanks.

Check timer time when changed it.

$
0
0
Hello. I have a question that i cant solve my self. I am making tower defence game and i added rapid fire upgrade that change time value in the time but its still the same speed because it does not check it when i buy that upgrade. How can i make that when i purchase it, it will check the timer after the upgrade is applied then it will start using the new time i hope you understand. I am using unity 5 beta pro. Here is the timer script: using UnityEngine; using System.Collections; public class TurretShooting : MonoBehaviour { public Rigidbody cannonball; public Transform cannonend; private float cannonballspeed = 1500f; public float firerate = 3.0f; public void Start () { InvokeRepeating("shootcannonball", 1, firerate); } void shootcannonball () { Rigidbody cannonballrig; cannonballrig = Instantiate (cannonball, cannonend.position, cannonend.rotation) as Rigidbody; cannonballrig.AddForce (-cannonend.forward * cannonballspeed); } } See that firerate in invokerepeating timer? yeah the upgrade change that value but it does not detect it and keeps using the old time. How can i make that it would check in this upgrade script: using UnityEngine; using System.Collections; using UnityEngine.UI; public class CannonRateOfFireUpgr : MonoBehaviour { private Databasestorage database; private int Cost = 15; public GameObject Cannon1; public GameObject Cannon2; // Use this for initialization public void increaserateoffire () { database = GameObject.Find ("Main Camera").GetComponent (); //Cannon3 = GameObject.Find ("Cylinder001").GetComponent (); //Cannon4 = GameObject.Find ("Cylinder001").GetComponent (); if (Cannon1.GetComponent ().firerate < 0.2f && Cannon2.GetComponent ().firerate < 0.2f) { transform.Find ("CannonRateOfFireText").GetComponent ().text = "Cannon Rate Of Fire\nMAX UPGRADED"; } else { if (database.money > Cost) { database.money -= Cost; Cannon1.GetComponent ().firerate -= 0.1f; Cannon2.GetComponent ().firerate -= 0.1f; //Cannon3.GetComponent().firerate -= 0.1f; //Cannon4.GetComponent().firerate -= 0.1f; Cost += 12; transform.Find ("CannonRateOfFireText").GetComponent ().text = "Cannon Rate Of Fire\nCost " + Cost; } } } } I tried adding the Start() in the button but it start a new timer and then its shooting 2 bullets at 1 time... that is bad. Soo how can i check it? sorry again if this is very confusing.

InvokeRepeating on object with DontDestroyOnLoad

$
0
0
I'm having an issue where I have a method that is invoked using InvokeRepeating, and whenever I change scenes the entire thing locks up. I've found that this is because within that repeating method I'm reading from a stream using ReadLine, which waits for the end of the line before proceeding. However, When I load my new scene it seems that the main thread takes over because the game locks up until I send that stream input, and which point it unlocks and then immediately locks back up waiting for more input. Any suggestions on how to fix this?.. I've already tried flushing the stream, closing the stream, and canceling the Invoke on the MonoBehaviours Awake method and then re-invoking it. I've also tried doing the same in the OnLevelWasLoaded method.

InvokeRepeating a trigger collider?

$
0
0
I have a trigger that is to damage any entity that passes through it I want to use InvokeRepeating to control delay of damage so it wont call it every frame this is my code using UnityEngine; using System.Collections; public class TriggerDamage : MonoBehaviour { public float DamageAmmount = 5.0F; public float Delay = 5.0F; void OnTriggerStay(Collider ent) { InvokeRepeating("Damage", 0f, Delay); } void Damage() { ent.gameObject.SendMessage("EntityDamage", DamageAmmount, SendMessageOptions.DontRequireReceiver); } } And this is my error Assets/Scripts/TriggerDamage.cs(17,17): error CS0103: The name 'ent' does not exist in the current context I understand the damage void has no reference to the collider name, so how can i do this? Or is there a better way than invoke repeating?

Shooting Projectiles With controlling attackSpeed

$
0
0
Hi I Have two Scripts ProjectileMotion and FSMArcherTower. I will brief you on how it works then ill tell you the problem. I Have attached both scripts to this tower and it shoots a projectile. Right now I have managed it to work almost the way i want but the code is a bit confusing. I have created a FSM in FSMArcherTower where In my update method I have Switch cases for different states of the tower. However I cannot call InvokeRepeating or StartCoroutine in update as it is called every frame. Thus I have called StartCoroutine In Start and created a while loop in the Co routine. The PROBLEM is that the code in public IEnumerator States() is not clean as attackSpeed variable is actually the input for yield waitForSeconds which if the value of attackSpeed is less causes to be actually More attack Speed. I just want a better way to use coroutines and Invoke and update in this situation. Any Insight will be helpfull. Thank you public class FSMArcherTower : MonoBehaviour { public enum ArcherTowerState { Idle, Attacking, Destroyed } public ArcherTowerState currentArcherTowerState; // Less is more speed // so 0.1f is faster attackSpeed than 0.9f public float attackSpeed = 0.5f; private bool canShoot; void awake() { } // Use this for initialization void Start () { currentArcherTowerState = ArcherTowerState.Idle; StartCoroutine (States()); } // Update is called once per frame void Update () { switch (currentArcherTowerState) { case ArcherTowerState.Attacking: // logic for attacking canShoot=true; Debug.Log("Attacking"); break; case ArcherTowerState.Idle: // what to do when idle canShoot = false; Debug.Log("Idle"); break; case ArcherTowerState.Destroyed: // what happens when destroyed Debug.Log("Destroyed"); break; } } public IEnumerator States() { while (true) { Debug.Log("True"); if (canShoot) { Invoke("callAttack",0.0001f); } if (!canShoot) { // what to do when idle CancelInvoke("callAttack"); } // } yield return new WaitForSeconds (attackSpeed); } } public void callAttack() { GetComponent().attack(); } } ProjectileMotion only create the projectile and its motion towards the target public class ProjectileMotion : MonoBehaviour { public GameObject Target; public float firingAngle = 45.0f; public float gravity = 9.8f; public GameObject Projectile; private Transform myTransform; void Awake() { myTransform = transform; Target = (GameObject)Instantiate (Target, transform.position + new Vector3(10,-3,0), Quaternion.identity); Target.name = "Capsule"; } void Start() { } public void attack() { StartCoroutine(SimulateProjectile()); } public IEnumerator SimulateProjectile() { // Instantiate projectile GameObject projectile = (GameObject)Instantiate (Projectile,myTransform.position, Quaternion.identity); Debug.Log ("Projectile initiated"); // Calculate distance to target float target_Distance = Vector3.Distance(projectile.transform.position, Target.transform.position); // Calculate the velocity needed to throw the object to the target at specified angle. float projectile_Velocity = target_Distance / (Mathf.Sin(2 * firingAngle * Mathf.Deg2Rad) / gravity); // Extract the X Y componenent of the velocity float Vx = Mathf.Sqrt(projectile_Velocity) * Mathf.Cos(firingAngle * Mathf.Deg2Rad); float Vy = Mathf.Sqrt(projectile_Velocity) * Mathf.Sin(firingAngle * Mathf.Deg2Rad); // Calculate flight time. float flightDuration = target_Distance / Vx; // Rotate projectile to face the target. projectile.transform.rotation = Quaternion.LookRotation(Target.transform.position - projectile.transform.position); float elapse_time = 0; while (elapse_time < flightDuration) { projectile.transform.Translate(0, (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime); elapse_time += Time.deltaTime; yield return null; } StartCoroutine (DestroyAfterWait (projectile)); } public IEnumerator DestroyAfterWait(GameObject projectile) { // destroy projectile after 0.5 sec yield return new WaitForSeconds (0.5f); if (projectile != null) { Destroy (projectile); } } void Update () { } }

how to instantiate UI image in unity2D

$
0
0
I'm making 2d racing game .... and I'm using UI image in the canvas background (road) .my car and enemy cars and I have tried to instantiate enemy car with this script by attaching this script to empty gameObject then attaching the enemy prefab to the enemyCar image that in the script...but the strange thing is :the enemyCar is instantiated in the hierarchy but I can't see it in the game What is the wrong ? is the wrong related to the child and parent or what ? and how can I make that UI image a child o canvas in the script ? using UnityEngine; using UnityEngine.UI; public class Generate : MonoBehaviour { public Image enemyCar; // Use this for initialization void Start() { InvokeRepeating("CreateEnemy", 1f, 1.5f); } void CreateEnemy() { Instantiate(enemyCar); } }

Opening and closing?

$
0
0
Hey Im trying to make a script where a jaw opens and closes every two seconds This is stays open for two - and closes for two I don't care if opening it is lerped or just instant but i cant seem to get the (C#) code to work. using UnityEngine; using System.Collections; public class Jaw : MonoBehaviour { private bool open; void OC() { open = !open; } void Example() { InvokeRepeating("OC", 2, 2F); } void Update () { if (open) { //open jaw Debug.Log ("open"); } else { // close jaw Debug.Log ("not open"); } } } (so far it just debugs "not open" every frame lol) Thanks in advance

how to decrease repeating time in invokerepeating?

$
0
0
In my below code, random object falls with Invokerepeating() finction. But the problem is, i want repeating time to be decreased with constantly repeating value from 1.0f to 0.5f with decreasing rate of 0.05f. So that, as time passes, the object start falling more fast and game becomes hard. How to do that? using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; public class Poolingscript2 : MonoBehaviour { public GameObject[] allprefabs; public List bullets ; public int listsize; GameObject go; // Use this for initialization void Start () { createlist (); InvokeRepeating ("fallobject", 2.0f,1.0f); } void createlist() { allprefabs = Resources.LoadAll ("Prefab"); for (int i=0; i

how to stop InvokeRepeating when it calls a function in 0.1 second?

$
0
0
Hello, i have InvokeRepeating to call a function (kills a monster and damage in 0.1second) the problem is when this monster is dead and he drops loot the invokeRepeating calls the loot function 5 times instead of one time only. i tried cancelinvoke but didnt work and i tried to check for a boolean and make it false inside the function but didnt work. i think the problem here is because the invokerepeating calls the function so many times before it cancels, so who can i stop that? here is an example of what i am saying: void Start () { InvokeRepeating("DoingDPS",0,0.1f); } void DoingDPS () // original function { MonsterHealth-=Dps; if(MonsterHealth<=0) { //Kill it and drop items } } void DoingDPS () //function with bool check { MonsterHealth-=Dps; if(MonsterHealth<=0) { if(DoOnce) { DoOnce=false; //Kill it and drop items } } } void DoingDPS () // function with cancelinvoke { MonsterHealth-=Dps; if(MonsterHealth<=0) { CancelInvoke("DoingDPS"); //Kill it and drop items } }

InvokeRepeating does not work in UNET

$
0
0
Well I am making a multiplayer 2D space shooter game and the player is supposed to shoot at a fixed rate when the screen is touched/held. It worked normally but when I began converting the game to multiplayer, the CmdShoot method does not work. (although it works without the invokeRepeat).. I tried to use coroutine but it said Command methods cannot be coroutines... so how should i shoot at a fixed rate then?

InvokeRepeating more turns?

$
0
0
I have 3 gameobjects and I want move a gameobject 3 second intervals this my script; public GameObject Player; public int a; Vector3 v3NextPos; GameObject enemys; int path; void Start () { InvokeRepeating ("direc",0.0f,3.0f); } void Update () { } void direc() { GameObject enemy1 = GameObject.Find ("Enemy1"); GameObject enemy2 = GameObject.Find ("Enemy2"); GameObject enemy3 = GameObject.Find ("Enemy3"); GameObject[] objectArray = {enemy1,enemy2,enemy3}; enemys = objectArray [Random.Range (0,3)]; Debug.Log (enemys); int path = Random.Range (1, 3); Debug.Log (path); if (path == 1) { v3NextPos.x = enemys.transform.position.x + a; v3NextPos.y = enemys.transform.position.y; v3NextPos.z = 20; enemys.transform.position = v3NextPos; } else { v3NextPos.y = enemys.transform.position.y + a; v3NextPos.x = enemys.transform.position.x; v3NextPos.z = 20; enemys.transform.position = v3NextPos; } v3NextPos = Vector3.zero; enemys = null; path = 0; } direc function 3 second intervals Calling but 5 times returning,I want just one return.

Perfect sinus

$
0
0
Hi, I'd like to be able to send a sinus to an external device . When launching my function, i start a timer : time Sinus = Stopwatch.StartNew (); To avoid Update, i used InvokeRepeating() And i compute: pos1 = float.Parse( Amplitude.text) * (Mathf.Sin (float.Parse(Frequency.text) *timeSinus.ElapsedMilliseconds / 1000f))); The probleme is that output is not constant : it works generaly well and sometime some part are completely missing (not go to greatest or lowest value)

Missing Reference Exception

$
0
0
Hi guys. I am trying to make a game object, in this case a battery, spawn around the room. i have created a cylinder with a battery texture and put it in the scene. using UnityEngine; using System.Collections; public class Battery_Script : MonoBehaviour { public Transform[] spawns; void Start () { InvokeRepeating("Spawn", 5 , 5); } void Spawn() { int i = Random.Range (0,spawns.Length); transform.position = spawns[i].position; transform.rotation = spawns[i].rotation; } } i have attached this script to it and i keep getting the error message "MissingReferenceException: The object of type 'Battery_Script' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. UnityEditor.GenericInspector.GetOptimizedGUIBlock (Boolean isDirty, Boolean isVisible, UnityEditor.OptimizedGUIBlock& block, System.Single& height) (at C:/buildslave/unity/build/Editor/Mono/Inspector/GenericInspector.cs:19) UnityEditor.InspectorWindow.FlushOptimizedGUIBlock (UnityEditor.Editor editor) (at C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorWindow.cs:1430)" i think its only being called once because collapse isn't checked on the console so i assume its happening on start. i don't destroy it at any point so i'm stumped. i'm sure i'm missing something obvious :) so thanks in advance.

Problem with InvokeRepeating (not the time to 0 bug)

$
0
0
Hello, I get an odd behaviour with this code : int i = 0; public void LaunchTimer() { InvokeRepeating("UpdateTimer", 0.0001f, 1); } protected void UpdateTimer() { Debug.Log(i); i++; } When I call LaunchTimer, it seems the repeating method is immediatly called between 2 and 5 times in a row, then things goes normal. Any help ?

Invokereapeating not calling function

$
0
0
So ive gone over several other unity answers and cannot seem to find why invokerepeating is not firing my function. I call it in the start function like this: void Start () { InvokeRepeating("LSCycle", 1f, 5f); } After that the code works as normal until i get to the LSCycle. Which looks like this: void LSCycle(){ Debug.Log("Life Support Cycle Started! c: "); //edit: emptied out the code between the debug.logs Debug.Log("Life Support Cycle Ended! c: "); } For some reason none of the debug.logs ever show up, and the numbers i try to update with the invoke do no update. I know its probably something incredibly simple but i cannot seem to find why it doesnt call. Any help would be appreciated. Thanks!

How can I get my platforms to randomly appear when not activated by button

$
0
0
So I'm building a game and the first puzzle is a jumping puzzle. I have already created a button collision so that when the player enters the trigger the platforms will appear for 8 seconds. However, when the button is not on I want my platforms to all appear at a random rate so if the player wants they can figure out the jumping puzzle without pressing the button. I have tried InvokeRepeating them so it happens every 0.5 seconds and it says "invoke method couldn't be called" I have also tried a coroutine and that doesn't work properly either. Any help would be appreciated :) Thanks :)![alt text][1] [1]: /storage/temp/55834-untitled.png

how can i increese the repete rate in invoke repeting after some time

$
0
0
IN my project am instantiating a sphere at initial stage with the repeat rate is 3f.after some i need to increase the speed instantiate no. what am doing is am decreasing the repeat rate after some time. Now what is the problem is the value is being initiated but there is no change. when i debug it it shows u can't initiate repeat rate in run time. note: am placing invoke-repeating in start function.

Optimization: how to do a checking less often than within an Update

$
0
0
Right now, this is my code (it is working): void Update() { if (Cardboard.SDK.Triggered) { Application.LoadLevel(Application.loadedLevelName); } } However, it is not needed to perform that check every frame. I'm trying to use the Update function as less as possible. It would be OK to perform that check every 0.5 seconds for instance. I have found the following possibilities: - [InvokeRepeating()][1]: I wonder if it would increase the performance somehow, or it uses Update internally. - [FixedUpdate()][2] after configuring Edit -> Project Settings -> Time -> Fixed Timestep: it would change the fixed timestep for the whole game, so I think it would not be a good idea. [1]: http://docs.unity3d.com/ScriptReference/MonoBehaviour.InvokeRepeating.html [2]: http://docs.unity3d.com/ScriptReference/MonoBehaviour.FixedUpdate.html

How to stop instantiate spawn ?

$
0
0
Anybody know how can i stop cloning object when the game finish / times up ? I'am using InvokeRepeating to clone object, this is the script : using UnityEngine; using System.Collections; public class SpawnerScript : MonoBehaviour { public float spawnTime = 5f; public float spawnDelay = 3f; public GameObject[] myPrefab; void Start () { InvokeRepeating ("Spawn", spawnDelay, spawnTime); } void Spawn() { // Instantiate a random prefab int notPrefabIndex = Random.Range (0, myPrefab.Length); Instantiate (myPrefab [notPrefabIndex], transform.position, transform.rotation); } } Thanks before..

Invoke is not working properly.

$
0
0
Hello, I am trying to create a bullet spawn using the invoke function but it is not working. Instead of creating a bullet every 3 seconds, it is waiting 3 seconds and then contionusly creating bullets non stop. Am I not using this function properly. Also, I am using the MobileSingleStickControl in the unity package as my shooting joystick. I have attached a trigger event on the joystick which is calling the "shoottrig" function below. It is using the PointerDown to set it to true, and PointerUp to set it to false. Here is the code, please help. Thanks. var shooting : boolean; var projectile : Rigidbody; var speed = 20; function Update () { //Face Joystick Direction var joystickHorizontal = UnityStandardAssets.CrossPlatformInput.CrossPlatformInputManager.GetAxis("Horizontal"); var joystickVertical = UnityStandardAssets.CrossPlatformInput.CrossPlatformInputManager.GetAxis("Vertical"); transform.LookAt(transform.position + Vector3(joystickHorizontal, 0, joystickVertical), -Vector3.forward); //Shooting triggered if(shooting){ Invoke("Shooting", 3.0f); } } //Creating shooting functions function Shooting(){ Debug.Log("we are shooting"); //TESTTTT var clone : Rigidbody; clone = Instantiate(projectile, transform.position, transform.rotation); // Give the cloned object an initial velocity along the current // object's Z axis clone.velocity = transform.TransformDirection (Vector3.forward * speed); } //Function called through the PointerDown trigger. function shoottrig(which : boolean){ shooting = which; }
Viewing all 220 articles
Browse latest View live


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