- Home /
void update working under conditions
let's say we have this script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class e : MonoBehaviour
{
private float rotZ;
void update()
{
if (Input.GetKeyDown("space"))
{
rotZ += Time.deltaTime * 1;
transform.rotation = Quaternion.Euler(0,0, rotZ);
}
}
if we assign this script to an object in unity, i thought it'd continuously rotate by the value of rotZ, but if we press space, it'll rotate only once and stop. i'm searching for something that would be an void update function that can continuously execute some task under certain conditions. is there any way to to this?
That's exactly what it's doing - If you change
if (Input.GetKeyDown("Space")) to if (Input.GetKey("Space"))
it will rotate constantly while holding space.
Answer by Bunny83 · Feb 02, 2021 at 08:28 AM
You probably are looking for GetKey instead of GetKeyDown. I would also recommend to use the KeyCode enum and not a key name as string constant.
void Update()
{
if (Input.GetKey(KeyCode.Space))
{
rotZ += Time.deltaTime * 1;
transform.rotation = Quaternion.Euler(0,0, rotZ);
}
}
GetKey will return true as long as the key is held down. GetKeyDown will only be true for one frame as it detects the "down" event. The same is true for GetKeyUp. It will only be true for one frame when the key is released.
So this example here will rotate the object continuously as long as the key is held down.
Of course if you want the object to keep rotating regardless of if the key is held down or not, you can do what @ GDGames0302 suggested. Though which solution is the right one depends on your exact usecase and your description is a big vague.