I’m trying to make a UI turn signal indicator using a UI image that I want to blink on and off with a click, click sound.
I can do it with an animation but is there a C# method that is a better way to do this so that when the game object is set active it will be blinking and making the classic “Click, Click” sound of a turn signal indicator?
I did something similar and made a Blink.cs class. Then attached it to whatever UI object I wanted to blink. Change the timing with the interval, etc. In this example, I just used AudioSource.PlayClipAtPoint to play your specified AudioClip at world origin.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
// this toggles a component (usually an Image or Renderer) on and off for an interval to simulate a blinking effect
public class Blink : MonoBehaviour {
// this is the UI.Text or other UI element you want to toggle
public MaskableGraphic imageToToggle;
public float interval = 1f;
public float startDelay = 0.5f;
public bool currentState = true;
public bool defaultState = true;
bool isBlinking = false;
public AudioClip clip;
void Start()
{
imageToToggle.enabled = defaultState;
StartBlink();
}
public void StartBlink()
{
// do not invoke the blink twice - needed if you need to start the blink from an external object
if (isBlinking)
return;
if (imageToToggle !=null)
{
isBlinking = true;
InvokeRepeating("ToggleState", startDelay, interval);
}
}
public void ToggleState()
{
imageToToggle.enabled = !imageToToggle.enabled;
// plays the clip at (0,0,0)
if (clip)
AudioSource.PlayClipAtPoint(clip,Vector3.zero);
}
}
You can use Coroutine to achieve this.
It would go something like this
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class BlinkingImage : MonoBehaviour {
Image image;
void Start ()
{
image = GetComponent<Image>();
StartBlinking();
}
IEnumerator Blink()
{
while (true)
{
switch(image.color.a.ToString())
{
case "0":
image.color = new Color(image.color.r, image.color.g, image.color.b, 1);
//Play sound
yield return new WaitForSeconds(0.5f);
break;
case "1":
image.color = new Color(image.color.r, image.color.g, image.color.b, 0);
//Play sound
yield return new WaitForSeconds(0.5f);
break;
}
}
}
void StartBlinking()
{
StopAllCoroutines();
StartCoroutine("Blink");
}
void StopBlinking()
{
StopAllCoroutines();
}
}
You can start a Coroutine, that toggle the alpha of your object and reproduce the sound then wait the time that you need.
Thanks @wilmer_lin and @RadioKnife Both of these were excellent answers and I loved them both. I ultimately could only choose one answer as the correct one even though they are both correct and both work. I ended up choosing the top answer simply because of the ease of use with the inspector values of being able to drag and drop and tweak parameters in the inspector.
I awarded points to both of you though because such help was well deserved on both parts,
Much MUCH thanks guys 