'I'm trying to change the color of a sprite when "space" is pressed but I want it to remain red for two seconds and than change back to blue
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Action : MonoBehaviour
{
SpriteRenderer sr;
public Color colorA = Color.red;
public Color colorB = Color.blue;
void Start()
{
sr=GetComponent<SpriteRenderer>();
}
void FixedUpdate()
{
if (Input.GetKeyDown("space"))
{
sr.color = colorA;
}
else sr.color = colorB;
}
}
This is the script I wrote. At first the sprite is blue and when SPACE is pressed it turns red, but the problem is that it doesn't stay red for more than a fraction of a second, sometimes it doesn't even turn red.
Solution 1:[1]
Take into account that int the fixed update, with GetKeyDown that returns true during the frame the user starts pressing down the key, you are setting the color, and the next frame you are turning it back.
Try with a coroutine, where you set the color back two seconds after.
void Update() {
if (Input.GetKeyDown("space"))
{
sr.color = colorA;
StartCoroutine(setColorWithDelay(2f));
}
}
IEnumerator setColorWithDelay(float delay) {
yield return new WaitForSeconds(delay);
sr.color = colorB;
}
Moreover, as commented FixedUpdate is used for physics. Use the Update instead.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
