Hi, I’m trying to control an object moving up slowly. Right now i’m using a key stroke, but eventually, I want to just call this method from script.
The following code works fine and the object moves up slowly. (For some reason it starts moving faster - but thats not my problem).
using UnityEngine;
using System.Collections;
public class WaveConroller : MonoBehaviour {
void Start () {
}
void Update () {
transform.Translate (Vector2.up * Time.deltaTime );
}
}
However, when I move this code to a method and call it using a keystroke, it happens instantaneously. If i increase my loop to something like t<50, and press the key, it waits, then moves the object way up instantly. As below.
using UnityEngine;
using System.Collections;
public class WaveConroller : MonoBehaviour {
private float t;
void Start () {
}
void Update () {
bool Up = Input.GetButtonDown ("Up");
transform.Translate (Vector2.up * Time.deltaTime );
if (Up)
MoveUp();
}
void MoveUp ()
{
t = 0f;
while (t<1)
{
t += Time.deltaTime;
transform.Translate (Vector2.up * Time.deltaTime );
Debug.Log (t);
}
}
}
Any Ideas?
Thanks!
I am not too sure about the problem… But is that you want to move the object up for some duration when the button Up is pressed? If so,
then maybe you can try the following code:
using UnityEngine;
using System.Collections;
public class WaveController : MonoBehaviour
{
private bool isMovingUp = false;
private void Update()
{
bool isInputUp = Input.GetKeyDown(KeyCode.UpArrow);
if (isInputUp && !isMovingUp)
{
StartCoroutine(MoveUp(1));
}
}
private IEnumerator MoveUp(float duration)
{
isMovingUp = true;
float t = 0f;
while (t < duration)
{
t += Time.deltaTime;
transform.Translate(Vector2.up * Time.deltaTime);
yield return null;
}
isMovingUp = false;
}
}
When you call MoveUp() method from Update, Update don’t wait till MoveUp(); finish. Its just simply go to next Update.
In next update, if you keep pressing Up button, its again getting called( MoveUp() method ) so there is 2 MoveUp() methods are running in memory, Since your while loop looking at t < 1 AND update is called nearly 60 times in Update if you kept press Up key 1 second there is 60 MoveUp() methods are executing in memory.
If I were you i will try something like following,