Time.deltaTIme does not work the way it should.
Hello everyone !
I'm trying to make a texture blend to one another in 5 sec when I press space. I have found a shader that works well on the forum everything goes the way I want but when I'm trying to update it in 5 sec with that code :
var timeLeft = 0.000;
var duration = 0.000;
function Start () {
}
function Update () {
if (Input.GetKeyDown("space")) {
// print("space key was pressed in Update");
while (duration <= 5) {
timeLeft += Time.deltaTime;
duration += Time.deltaTime;
// print(timeLeft);
// print(duration);
var lerp = Mathf.PingPong (timeLeft, duration) / duration;
GetComponent.<Renderer>().material.SetFloat( "_Blend", lerp );
}
}
else if (duration >= 5) {
duration = 0;
}
}
It just change my texture in one frame and I don't know why, shouldn't it be doing it in 5sec (as duration has +Time.deltaTime everyframe?).
Thanks in advance
You should never add a while loop (or any loop) in Update, because it runs every frame, and loops can take more than 1 frame to complete, so in general, doing it that way seems to me like a bad idea.
Also, Time.deltatime really only represents - as far as im aware the "second" equivilent based on the frames the game is running at or settings its being played at, so you may need to do duration += 1 * Time.deltaTime
, saying more "add 1, over the course of 1 delta time second".
Hi Dibbie first thanks for this fast answer ! I've read that I shouldn't be using a loop inside Update $$anonymous$$aybe I should be using a coroutine? Never tried that don't really know how to do it yet.
Then I've tried to put duration += 1 * Time.deltaTime but nothing changes, I don't get why :(
Answer by chon59 · Jul 06, 2016 at 03:08 PM
I've achieved this by doing a coroutine in C#
here it is if someone needs it :
using UnityEngine;
using System.Collections;
public class coroutine : MonoBehaviour {
float timeLeft = 0;
float duration = 0;
float blending = 5;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown("space"))
{
if (duration >= 5)
{
duration = 0;
StartCoroutine("corout");
}
else
{
StartCoroutine("corout");
}
}
}
IEnumerator corout()
{
while (duration <= 5)
{
timeLeft += Time.deltaTime;
duration += Time.deltaTime;
print("timeLeft" + timeLeft);
print("duration" + duration);
var lerp = Mathf.PingPong(timeLeft, blending) / blending;
GetComponent<Renderer>().material.SetFloat("_Blend", lerp);
yield return null;
}
}
}
Your answer
Follow this Question
Related Questions
Light intensity Lerp not functioning properly 1 Answer
Time.deltaTime and difference of Time.time not matching 0 Answers
Is Time.deltaTime different on various devices? 0 Answers
How do I do math in unity.(timer/60 and timer%60) 1 Answer
Animation window time bar shows 1 minute increments - HELP 0 Answers