Hi. In my game I have a player climbing up a wall and objects fall on the player. (Credits to @static_cast). I was wondering how I can increase the spawn rate of the object every 30 seconds. In other word to make more objects fall as the game goes on. How should I do this?
↧
Increasing Spawn Rate as Game Goes On
↧
Recharge delay on shield regen through coroutines
I'm trying to implement a recharge delay for my energy shield class using coroutines. The idea is to reset duration of the delay each time damage is received. I've got this code so far:
public class ShieldStats : MonoBehaviour {
public float currentShield = 0;
public float maxShield = 100f;
public float rechargeRate = 0f;
public float rechargeDelay = 0f;
public float rechargeDelay = 0f;
private bool shieldRechargeAllowed = true;
void Start () {
InvokeRepeating ("RechargeShield", 1, 0.1f);
}
public float ApplyDamage (float damage) {
StartCoroutine (DisallowShieldRegenForXSeconds (rechargeDelay));
......
}
public void RechargeShield () {
if (shieldRechargeAllowed && currentShield < maxShield) {
currentShield += rechargeRate;
if (currentShield > maxShield)
currentShield = maxShield;
}
}
void OnDisable () {
CancelInvoke ("RechargeShield");
}
IEnumerator DisallowShieldRegenForXSeconds (float rechargeDelay) {
shieldRechargeAllowed = false;
yield return new WaitForSeconds (rechargeDelay);
shieldRechargeAllowed = true;
}
}
Thing is, each time damage applied - new coroutine is instantiated. When the damage is received after old coroutine yield's it creates new coroutine which sets flag to false, but when old coroutine starts again - it sets bool to true, where it should be false.
Is there a way to stop previous coroutine instances and keep only latest one called? Or should I use deltatime for this purposes?
↧
↧
Why is InvokeRepeating not working in boolean method?
I'm trying to kill two birds with one stone by putting some logic in a boolean method. By itself the boolean method does what it's supposed to. The CancelInvoke works as well. However, with the InvokeRepeating there, it doesn't work or return true. I have to manually change the distance to make it true. What is wrong?
float range = 5f; //The Range
private bool InRange () {
if (Vector2.Distance(transform.position, targetPosition) <= range) { //Get Distance
if (!IsInvoking("TheMethod")) { //Incase not invoking
InvokeRepeating("TheMethod", .5f, .5f); //Doesn't work and doesn't return true
}
return true;
} else {
CancelInvoke("TheMethod"); //cancels invoke
return false;
}
}
↧
InvokeRepeating and rotations
I have an object rotating around the Earth which needs to create new instances of a prefab using InvokeRepeating, in front of the object (in view of camera, also rotating).
The method I am calling in InvokeRepeating uses the following code:
var currTrans = this.transform;
var currPos = currTrans.position;
GameObject sat = (GameObject) Instantiate(marsSat, currPos, Quaternion.identity );
sat.transform.RotateAround (currPos, currTrans.right, 270);
sat.transform.RotateAround (currPos, currTrans.up, 270);
sat.transform.RotateAround (origin, currTrans.right, 20);
sat.transform.RotateAround(origin, currTrans.forward, Random.Range(-2.5f, 2.5f));
I firstly create the new object.
Then attempt to align the prefab to face the camera.
Then attempt to rotate the prefab 20degrees so it appears in front of the camera (initially created on top of it), and then to add a random sideways displacement.
The code works perfectly for the first instance, but afterwards all new objects created have some extra rotation added, and are no longer facing the camera, and by half way round the object is completely on its side etc.
↧
GUIText not updating score....
So I got this guitext that holds my score, and depending on the distance that the player has traveled before he (inevitably) dies, the score updates. But for some reason, when i press the lovable play button, The score GUI is there, but it doesn't update. Not only that, its weird because what is displayed is the final score from the last time the game is played. For example, if you play one game, and die at at 254 meters, when you press "Try Again" (this reloads the scene through Application.LoadLevel), it starts again with the score GUI saying "Score: 254". From then on it doesn't update.
My code to hold the score is below:
using UnityEngine;
using System.Collections;
public class ScoreScript : MonoBehaviour {
//Scores
private double startPos = 0;
private double currentPos;
private int score;
//Score Stuffs
public GUIText CurrentScore;
// Use this for initialization
void Start () {
score = 0;
Instantiate(CurrentScore, new Vector3 (0.35f, 1f, 0f), Quaternion.identity);
}
// Update is called once per frame
void Update () {
currentPos = (int)(transform.position.x);
score = currentPos;
print (""+score);
CurrentScore.text = "Score: " + score.ToString();
}
}
↧
↧
InvokeRepeating not stopping after object set to inactive. Any workaround ?
When Object A spawns Object B, after 1 second, Object B spawns Object C using InvokeRepeating. I have my InvokeRepeating code on Object B, so that whenever Object B becomes active, it spawns Object C. When Object B touches an enemy object, it becomes deactivated, but it still continues to spawn Object C even after being deactivated. A few seconds later, Object A spawns Object B again, but InvokeRepeating is running already and doesn't spawn Object C at the correct time. If I make it so, that when Object B touches an enemy object, it should CancelInvoke the InvokeRepeating code, then InvokeRepeating never gets called again ever. Are there any workarounds to this ? Here is my code:
void Start () {
InvokeRepeating("Spawn", spawnDelay, spawnTime);
missiles = new List ();
for (int i = 0; i < pooledAmount; i ++)
{
GameObject obj = (GameObject)Instantiate(missile);
obj.SetActive(false);
missiles.Add (obj);
}
void Spawn ()
{
for(int i = 0; i < missiles.Count; i++)
{
if (!missiles[i].activeInHierarchy)
{
missiles[i].transform.position = transform.position;
//missiles[i].transform.rotation = transform.rotation;
missiles[i].SetActive(true);
break;
}
}
}
↧
Where to run InvokeRepeating?
I would like to invokerepeating and instantiate some prefabs based on the current (and changing) value of BallController.score
void Start(){
if (BallController.score>100)
{
InvokeRepeating("Blockers", 1f, 1f);
}
}
void Blockers() {
if (BallController.score > 100)
{
Instantiate(MakinBlockers);
}
}
Currently my code only starts InvokeRepeating("Blockers") if the game is stopped and started over again with a score of more than 100. Where do I need to put InvokeRepeating to make it check the score more often?
↧
How to change variables of InvokeRepeating ?
I'm spawning enemies at the start by using InvokeRepeating. As the game progresses, I wish to spawn enemies faster and hence reduce the spawnTime. Since my InvokeRepeating is run only once in the void Start(), I'm unable to edit the spawnTime variable. How is something like this achieved ?
public float spawnTime = 5f; // The amount of time between each spawn.
public float spawnDelay = 3f; // The amount of time before spawning starts.
void Start ()
{
// Start calling the Spawn function repeatedly after a delay.
InvokeRepeating("Spawn", spawnDelay, spawnTime);
}
↧
calling in a function once every given seconds
i'm trying to make a whacamole game and i want to spawn moles once every one second until score is ten,twice in a second when score is less than 25 and so on....
this doesn't seem to be working as inteded and i have no clue why(my guess is the invokerepeating function but i don't know how to fix it)any help would be appreciated
using UnityEngine;
using System.Collections;
public class MoleInstantiate : MonoBehaviour {
// Use this for initialization
public int moleChoose;
public int lastChoose;
public GameObject[] mole= new GameObject[8];
void Start () {
callMoler ();
}
void callMoler(){
if (ScoreCounter.countScore < 10) {
InvokeRepeating ("moler", 2, 1.0f);
} else if (ScoreCounter.countScore > 10 && ScoreCounter.countScore < 25) {
InvokeRepeating ("moler", 0, 0.5f);
} else if (ScoreCounter.countScore > 25 && ScoreCounter.countScore < 51) {
InvokeRepeating ("moler", 0, 0.33f);
} else {
InvokeRepeating ("moler", 0, 0.25f);
}
}
void moler(){
moleChoose = Random.Range (0, 8);
while(moleChoose!=lastChoose)
{
mole [moleChoose].gameObject.SetActive (true);
lastChoose = moleChoose;
}
}
}
↧
↧
instantiate prefabs/gameObjects
Hi, im developing a 2d game.
im using this code to invoke three different kind of objects ramdomly to the scene.
#pragma strict
var posible_col = new Array();
var col : GameObject;
function Start()
{
posible_col[0] = GameObject.Find ("f_col_1");
posible_col[1] = GameObject.Find ("f_col_2");
posible_col[2] = GameObject.Find ("f_col_3");
InvokeRepeating("next_col", 2, 3);
}
function next_col ()
{
col = posible_col[Random.Range(0,3)];
Instantiate(col, new Vector2(0 , 9), Quaternion.identity);
}
-------------------------------------------------------------
it works fine, but it does not instantiate a prefab! i can see at the inspector that the object invoked is not a prefab because the cube besides the drop-down tags option, is not blue but green, blue and red (the components of the object invoked are the same as the prefab!).
im using another script that has a OnCollisionEnter2D funtion on it, it works untill i use this one. And the tests i've made so far, show that this collision script only works when the colliders are prefabs, i dont know why, but when two of these invoked objects collide, apearly it does not detect the collision and so nothing happens.
the names i used when GameObject.Find are the names of my prefabs, ¿why it instantiate an object?
¿is there something wrong about this code i've posted, that could interfere with the other one?
thanks for your help!
↧
InvokeRepeating not working?
I am very new and I just don't understand why this code doesn't do anything even thou it doesn't show any errors.
InvokeRepeating("flash",5,5);
function flash(){
light.enabled=true;
yield WaitForSeconds(0.1);
light.enabled=false;
}
function Start () {
}
function Update () {
}
I want my light to turn on and off every 5 seconds.
Kind Regards,
↧
InvokeRepeating doesn't work
I have this script, and it gives me these errors. What is wrong?
Thanks!
***Assets/MyClass.cs(9,37): error CS1519: Unexpected symbol `RandomValue' in class, struct, or interface member declaration***
***Assets/none.cs(17,17): error CS0178: Invalid rank specifier: expected `,' or `]'***
using UnityEngine;
using System.Collections;
public class MyClass : MonoBehaviour {
GameObject[] non;
int i = 0;
InvokeRepeating("Activator", 0.1f, 0.1f);
void Activator() {
i++;
if(i >= non.Length)
{
i = 0;
}
non[!=i].SetActive(false);
}
}
↧
Weapon reload timer problem.
i tried to write a weapon fire script, that also has an automatic reload timer, it works well, shoots the bullets, substracts 1 ammunition, and then waits X seconds until it can fire again with the ammo reloaded. The problem is that when it reloaded and has X amount of bullets again, it wont substract anymore, so the second round is infinite. any ideas what i am doing wrong?
using UnityEngine;
using System.Collections;
public class NewWeaponManager : MonoBehaviour {
public GameObject parent;
public GameObject muzzle;
public Texture[] muzzleTexture;
public Rigidbody bulletPrefab;
public bool fireWeapon;
public float velocity = 10.0f;
public float weaponSpeed = 0.1f; // Speed of weapon.
public float weaponScattering = 0.005f;
public bool isSpawning = false;
public int currentAmmunition;
public int maxAmmunition = 25;
public bool muzzleFlashEnabled = false;
public bool reloadWeapon = false;
// Use this for initialization
void Start () {
currentAmmunition = maxAmmunition;
}
// Update is called once per frame
void Update () {
if (muzzleFlashEnabled == true) {
muzzle.gameObject.SetActive(true);
} else {
muzzle.gameObject.SetActive(false);
}
if (currentAmmunition <= 0) {
reloadWeapon = true;
StartCoroutine (ReloadWeapon (5));
CancelInvoke("SpawnBullet");
}
if (fireWeapon == true && isSpawning == false) {
if (reloadWeapon == false) {
muzzleFlashEnabled = false;
isSpawning = true;
InvokeRepeating ("SpawnBullet", 0.001f, weaponSpeed);
}
} else if (fireWeapon == false) {
muzzleFlashEnabled = false;
CancelInvoke("SpawnBullet");
isSpawning = false;
}
}
void SpawnBullet() {
muzzleFlashEnabled = true;
float randomDirX = Random.Range (-weaponScattering, weaponScattering);
float randomDirY = Random.Range (-weaponScattering, weaponScattering);
Quaternion ScatterDirection = new Quaternion (transform.rotation.x + randomDirX, transform.rotation.y + randomDirY, transform.rotation.z, transform.rotation.w);
currentAmmunition -= 1;
Rigidbody newBullet = Instantiate(bulletPrefab, transform.position, ScatterDirection) as Rigidbody;
newBullet.AddForce(transform.forward*velocity, ForceMode.VelocityChange);
newBullet.GetComponent().parentWeapon = gameObject;
}
public IEnumerator ReloadWeapon(float timer) {
yield return new WaitForSeconds (timer);
reloadWeapon = false;
currentAmmunition = maxAmmunition;
}
}
↧
↧
Invokerepeating and itween problems
hello Im making a script with itween here is the script:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class RotateBy : MonoBehaviour {
public float snelheid = 2F;
public AudioClip geluid;
void Start () {
audio.clip = geluid;
audio.loop = true;
audio.Play ();
iTween.RotateBy (gameObject,iTween.Hash (
"x", 2,
"speed", snelheid
));
}
void Example () {
InvokeRepeating ("Faster", 2, 0.3F);
}
I want The InvokeReating thing on the "snelheid" thing In rule 17 I want that the object with this script goes faster and faster but fail. can anyone help me?
↧
Trying to Invoke method: Spawner.SpawnObject couldn't be called.
I don't have an error, it just says:
Trying to Invoke method: Spawner.SpawnObject couldn't be called.
This is the script:
#pragma strict
// The object to be spawned
var SpawnObject : GameObject;
// in seconds
var SpawnStartDelay : float = 0;
var SpawnRate: float = 5.0;
function Start()
{
InvokeRepeating("SpawnObject", SpawnStartDelay, SpawnRate);
}
// Spawn the SpawnObject
function Spawn()
{
Instantiate(SpawnObject, transform.position, transform.rotation);
}
Thanks in advance! :)
↧
what to make invoke repeating starts from the point where the scene changes???/
i have used invoke repeating to add money after every 20 sec.But when scene changes invoke repeating starts from zero.What to do to make invoke repeating starts from the point where the scene changes???/
↧
Lost gameobject prefab reference in InvokeRepeating
Hi.
I create prefabs in invoke repeating but I want keep a distance beetween them, for this reason I need keep/save the last prefab created. The surprise appear when in senconds invokes the last prefab created is lost, and always return the coordenates of the first.
public class GenerateStairs : MonoBehaviour {
public GameObject stair=null;
private GameObject stair_last=null;
public float last_y_stair_cor=0;
// Use this for initialization
void Start()
{
Debug.Log ("Start");
InvokeRepeating("CreateObstacle", 1f, 4f);
}
void CreateObstacle()
{
Debug.Log ("CreateObstacle");
int number = Random.Range (1, Screen.width);
Vector3 pos = new Vector3 (number, -10, 0);
Vector3 posScreen = Camera.main.ScreenToWorldPoint (pos);
posScreen.z = 0;
if (stair_last != null)
{
Debug.Log ("CreateObstacle INI last_y_stair_cor " + last_y_stair_cor);
last_y_stair_cor = (float)stair_last.transform.position.y;
Debug.Log ("CreateObstacle INI bucle (float)stair.transform.position.y / posSceen.y / last_stair_cor " + (float)stair_last.transform.position.y + "/" + posScreen.y + "/" + last_y_stair_cor);
}
if (last_y_stair_cor != 0)
{
posScreen.y = last_y_stair_cor - (float)stair.renderer.bounds.extents.y * 2;
}
Debug.Log ("CreateObstacle2 bucle posSceen.y / last_stair_cor " + posScreen.y + "/" + last_y_stair_cor);
Debug.Log ("CreateObstacle2 stair position " + posScreen);
stair = (GameObject)Instantiate (stair, posScreen, Quaternion.identity);
if (last_y_stair_cor != 0)
{
posScreen.y = last_y_stair_cor - (float)stair.renderer.bounds.extents.y * 2;
}
Debug.Log ("CreateObstacle3 bucle posSceen.y / last_stair_cor " + posScreen.y + "/" + last_y_stair_cor);
Debug.Log ("CreateObstacle3 stair position " + posScreen);
stair_last = (GameObject)Instantiate (stair, posScreen, Quaternion.identity);
if (stair_last != null) {
last_y_stair_cor = (float)stair_last.transform.position.y - (float)(float)stair_last.renderer.bounds.extents.y * 2;
Debug.Log ("CreateObstacle stair_last bucle posSceen.y / last_stair_cor " + posScreen.y + "/" + last_y_stair_cor);
Debug.Log ("CreateObstacle stair_last stair position / (float)stair_last.transform.position.y " + posScreen + "/" + (float)stair_last.transform.position.y);}
}
// Update is called once per frame
void Update () {
}
}
↧
↧
InvokeRepeating is not stoping.
I am trying to make enemy spawn using InvokeRepeating but any how i am not able to stop it when i have enough number of enemy
Here is the code can any one tell me what went wrong.
public GameObject enemy; // The enemy prefab to be spawned.
public float spawnTime = 7.0f; // How long between each spawn.
public Transform[] spawnPoints; // An array of the spawn points this enemy can spawn from.
public int LevelMaxEnemy=10;
public int numofEnemy=0;
void Start ()
{
// Call the Spawn function after a delay of the spawnTime and then continue to call after the same amount of time.
InvokeRepeating ("Spawn", spawnTime, spawnTime);
}
void Spawn ()
{
// If the player has no health left...
if(PlayerMovementScript.playerHealth <= 0f)
{
// ... exit the function.
return;
}
if(numofEnemy > LevelMaxEnemy){
// ... exit the function.
return;
}
else{
// Find a random index between zero and one less than the number of spawn points.
int spawnPointIndex = Random.Range (0, spawnPoints.Length);
// Create an instance of the enemy prefab at the randomly selected spawn point's position and rotation.
Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
numofEnemy = numofEnemy + 1;
}
}
↧
How many InvokeRepeating are okay?
In theory it is possible in my game to have at max. 4096 InvokeRepeating active. So is this any problem? I mean I tested it already there was no problem. I just wanted to know if it ok to use it so excessively.
InvokeRepeating("Income",0f,1f);
void Income()
{
gc.playerMoney += incomeResult;
}
The other way would be to go through the list of times with a for loop and get the tiles that generate income and get the value (each second).
↧
fast input and high fps
I want my game to react quickly to keyboard input. Graphics has a greate effect on Update fps, so I choose InvokeRepeating to run my logic(can I use FixedUpdate? Any suggestion?). Input of Unity is based on Update so I use GetAsyncKeyState to detect keyboard input(is there any batter solution?).
But the problem is even though logic fps is high, delta time of logic fps may be long, especially the frame I push keyboard. If every frame I push keyboard delta time is long, the game may feel lag. And the fps of InvokeRepeating is not exactly I set, but effect by Fixed Timestep. If I call InvokeRepeating("test", 0.001f, 0.005f), test will not run at 200fps, but if I change Fixed Timestep to a small number, It can be.Can anyone explain this to me? Thank you!
↧