Using yield return new WaitForSeconds(waitTime);
within an IEnumerator, what is the shortest wait time other than 0? I have tried using a float number and have tried as low as 0.00001f for the waitTime, however i'm not sure if there is a limit or not?
The purpose is that I am having a player's coins added one unit at a time, so the meter is 'filling up' rather than instant. I have tried searching but I cannot seem to find the answer to what the shortest limit is for WaitForSeconds, so if anyone knows I'd greatly appreciate the answer.
Additionally, my code is as follows if anyone has any input on how I can speed up the process without making it instant, as it's just not quite quick enough and the player is having to sit for a while waiting for the coins to be added to the meter at the end of the game.
IEnumerator AddCoins()
{
yield return new WaitForSeconds(1);
while (userGainedCoins > 0)
{
if (addingSoundPlaying == false)
{
addingSound.Play();
addingSoundPlaying = true;
}
if (userGainedCoins == 1)
{
addingSound.Stop();
}
userCoins += 1;
userGainedCoins -= 1;
PlayerPrefs.SetInt("User Coins", userCoins);
yield return new WaitForSeconds(waitTime);
}
addingSoundPlaying = false;
}
I think it doesn't have a minimum time, it just waits until it reaches a certain amount before waiting. If you want, you can just add multiple coins at a time. I usually try not to mess with these kinds of things, and instead of messing with the coins, I would just mess with the value it displays. You could have a script that holds the number of coins and increases/decreases it based on the timestep. Something like this:
public int coins = 100;
public int displayedCoins = 0;
private void Update() {
int change = Mathf.CeilToInt(300 * Time.deltaTime);
if (displayedCoins < coins)
displayedCoins = Math.Min(displayedCoins + change, coins);
else
displayedCoins = Math.Max(displayedCoins - change, coins);
}
and with this you can just set the amount and forget about it, and it works with gaining and losing coins. You can also change the change value to something like int change = Mathf.CeilToInt(Mathf.Abs(coins - displayCoins) * Time.deltaTime) to make it have an ease-out effect, or whatever you want. (I didn't test this code.)
Related
I am currently working on an idle game but am having trouble with time. The code below runs when a business is activated in order to prevent the player activating the business again before it finishes. The variable "subtractTime" is the time it takes for the business to finish multiplied by 100.
There are different kinds and levels of businesses that require a different amount of time each. When you upgrade the business to certain levels, the time it takes to make money cuts in half.
When the time is lower than a second, the code below works as it is fast enough to not be able to tell it can't keep up. However, when dealing with larger amounts of time, such as 6 seconds, it does not subtract fast enough.
while (subtractTime > 0)
{
completed = false;
yield return new WaitForSeconds(.01f);
subtractTime = subtractTime - 1;
}
There are multiple ways to achieve that.
One simple way is to just wait until the timer has finished:
IEnumerator StartCooldown(float subtractTime) {
subtractTime *= 0.1f;
completed = false;
yield return new WaitForSeconds(subtractTime);
completed = true;
}
The only problem with this is that you don't have the remaining time updated as time passes, which may be useful for other things such as a cooldown bar.
A workaround to that would be something like this:
IEnumerator StartCooldown(float subtractTime) {
subtractTime *= 0.1f;
completed = false;
while (subtractTime > 0) {
subtractTime -= Time.deltaTime;
yield return null;
}
completed = true;
}
Time.deltaTime is just the time elapsed between the last frame and the current one, and yield return null just stops the execution of the Coroutine and resumes it on the next frame.
Note: you can remove the subtractTime *= 0.1f; line in both examples if the value you pass to the function is in seconds, since both examples work with time measured in seconds :)
The problem is the fixed time WaitForSeconds(.01f) because you don't know if the players' CPU can keep to that schedule, it may be too slow or be busy on other tasks. Instead we use the time it took to complete the game loop each frame, which is called Time.deltaTime:
IEnumerator ITimeSomething(float timeLimit)
{
float t = 0;
while (t < timeLimit)
{
t+= Time.deltaTime;
yield return null;
}
// do something when the time runs out
}
Hey so I've been working on this damage over time code for quite awhile now, I've used MANY online resources, and I have tons of iterations of trying this, and it hasn't worked, so I come here.
DISCLAIMER: My object does not get destroyed when yielding, it just hits the yield, and nothing happens.
if(CurrentStatus == Status.Burning && burning==false){
burning=true;
StartCoroutine (DamageOverTimeCoroutine(100, 5));
Debug.Log("what");
burning = false;
//CurrentStatus = Status.Empty;
}
public IEnumerator DamageOverTimeCoroutine(float damageAmount, float duration){
float amountDamaged = 0;
float damagePerLoop = damageAmount / duration;
while (amountDamaged < damageAmount) {
int numInt = (int)Math.Ceiling(damagePerLoop);
enemyCurrentHealth -= numInt;
var clone = (GameObject) Instantiate(damageNumber, this.gameObject.transform.position, Quaternion.Euler(Vector3.zero));
clone.GetComponent<FloatingNumbers> ().damageNumber = numInt;
amountDamaged += damagePerLoop;
yield return null;
Debug.Log(amountDamaged);
}
if(amountDamaged>damageAmount){
//StopCoroutine(DamageOverTimeCoroutine());
}
CurrentStatus = Status.Empty;
burning=false;
}
To reiterate, it does the damage, and then quits on the yield return, I've changed it from WaitSeconds just to see if it would work any other way, it does not. I've never had the Debug after the yield fire. Why is this happening?
Would be much appreciated,
Thanks
Figured it out, the
var clone = (GameObject) Instantiate(damageNumber, this.gameObject.transform.position, Quaternion.Euler(Vector3.zero));
clone.GetComponent ().damageNumber = numInt;
lines short circuted it without throwing a error. Odd, but it works now. Thanks for the input guys
I don't know if this is an easy question or not.
I'm trying to write a single function that slows down the player and returns them to normal speed after a certain amount of time. I founds some answers online but they all use a second function to set a timer, but I'm trying to contain the whole thing in one function.
I've already tried this:
public void slowDown(float slowAmount, float durationSlowed)
{
var playerInfo = player.GetComponent<FPSMovement>();
playerInfo.speed *= slowAmount;
float lengthSlowed = Time.time + durationSlowed;
if(Time.time > lengthSlowed)
{
playerInfo.speed /= slowAmount;
}
}
and calling it with:
slowDown (0.5f, 2f)
It manages to slow down the player, but doesn't return their speed to normal.
What am I missing here?
I assume this is unity.
You probably want to do it with IEnumerators and Coroutines. They distribute code to be executed over multiple frames. Something like this:
IEnumerator SpeedUp() {
speed *= 2;
yield return new WaitForSeconds(2.0f);
speed /= 2;
}
void Update (){
if(Input.GetKeyDown(***YOUR KEY HERE***)) {
StartCoroutine(SpeedUp());
}
}
This will double the speed of your character, wait 2 seconds, and halve it. If you want to add a cooldown to the amount of times you can add speed, just drop a boolean check.
So when my character gets hit by the enemies fire breath, I want to create the feel of the character being set on fire. So while the character is on fire I want him to lose a specific amount of health for a specific amount of time.
For example; lets say he is on fire for 3 seconds and I want to make him lose 30 health for being on fire, how would I evenly distribute losing 30 health for 3 seconds? I dont want the 30 damage to be applied instantly to the health, I want it to slowly tick away at the players health so that at the 3 second mark 30 damage has been dealt.
The game is being made with c#.
Thanks.
This is just like moving Gameobject over time or doing something over time. The only difference is that you have to use Mathf.Lerp instead of Vector3.Lerp. You also need to calculate the end value by subtracting the value you want to lose over time from the current value of the player's life. You pass this into the b or second parameter of the Mathf.Lerp function.
bool isRunning = false;
IEnumerator loseLifeOvertime(float currentLife, float lifeToLose, float duration)
{
//Make sure there is only one instance of this function running
if (isRunning)
{
yield break; ///exit if this is still running
}
isRunning = true;
float counter = 0;
//Get the current life of the player
float startLife = currentLife;
//Calculate how much to lose
float endLife = currentLife - lifeToLose;
//Stores the new player life
float newPlayerLife = currentLife;
while (counter < duration)
{
counter += Time.deltaTime;
newPlayerLife = Mathf.Lerp(startLife, endLife, counter / duration);
Debug.Log("Current Life: " + newPlayerLife);
yield return null;
}
//The latest life is stored in newPlayerLife variable
//yourLife = newPlayerLife; //????
isRunning = false;
}
Usage:
Let's say that player's life is 50 and we want to remove 2 from it within 3 seconds. The new player's life should be 48 after 3 seconds.
StartCoroutine(loseLifeOvertime(50, 2, 3));
Note that the player's life is stored in the newPlayerLife variable. At the end of the coroutine function, you will have to manually assign your player's life with the value from the newPlayerLife variable.
I suppose, what you are looking for is a Coroutine. Check out here and here for the documentation. It will allow you to do your custom health reducing actions separately from update function. Using coroutines you can make something happening by ticks, and you can determine how much time the tick is.
You could use couroutines. Something like this:
void OnHitByFire()
{
StartCoroutine(DoFireDamage(5f, 4, 10f));
}
IEnumerator DoFireDamage(float damageDuration, int damageCount, float damageAmount)
{
int currentCount = 0;
while (currentCount < damageCount)
{
HP -= damageAmount;
yield return new WaitForSeconds(damageDuration);
currentCount++;
}
}
So this is what I ended up doing. It causes the character on fire to lose 30 health and you can see the health ticking down instead of it happening over intervals.
IEnumerator OnFire()
{
bool burning = true;
float timer = 0;
while (burning)
{
yield return new WaitForSeconds(0.1f);
hp -= 1;
timer += 0.1f;
if (timer >= 3)
{
burning = false;
}
}
}
I am trying to make a game which "kind of" simulates the shooting of the "worms" game. The player can choose the position (circular) of an object and then, the force that is applied to the object should move in the direction its pointing towards. I tried using the AddForce(transform.right) code, but it would just go to the right. (2D BoxCollider and RigidBody2D)
Then comes the hard part, making the player choose the force by charging the power. When the player holds down the "f" key, I want the power to go up to a certain point. Once it reaches that point, I want it to go down again and then up again, so the player can choose the power he wants. I have no idea how to go about this.
It's been awhile since I've did Unity coding, so there may be some minor errors with my syntax but it should give you an idea of how to accomplish this. Your best bet for the loop is to use a coroutine to not block the main thread.
in Update() check for 'on key down' for F and start this coroutine:
IEnumerator Cycle()
{
float max = 10.0f;
float min = 1.0f;
float interval = 0.5f;
do
{
for(int i=min;i<max;i++)
{
PowerValue = i;
yield return new waitforseconds(interval);
if(!input.getkey(f))
break;
}
for(int i=max;i>min;i--)
{
PowerValue = i;
yield return new waitforseconds(interval);
if(!input.getkey(f))
break;
}
} while(input.getkey(f));
}
And back in update() use that powerValue with getKeyUp(f)
And here is PowerValue setup as a parameter that prevents code from setting the max and min outside of a 1 to 10 range (configurable)
private float powerValue = 1.0f;
public float PowerValue
{
get { return powerValue; }
set {
if(value>10f)
powerValue=10f;
else if (value<1f)
powerValue=1f;
else
powerValue=value;
}
}