- Home /
How to start a courine with input from keyboard
I have the code below which basically takes multiple audio sources as a game object and play the audio sources randomly one after another by removing the ones that already been played so not to repeat
public class RanodmAudioObjects : MonoBehaviour
{
public List<AudioSource> sourcesInScene; //assign these in the inspector
void Start()
{
StartCoroutine(SoundsTick());
}
IEnumerator SoundsTick()
{ //we're using an ienumerator so we can "wait" between loops.
while (true)
{
for (int x = 0; x < sourcesInScene.Count; x++)
{
yield return null;
x = Random.Range(0, sourcesInScene.Count);
sourcesInScene[x].Play();
sourcesInScene.RemoveAt(x);
yield return new WaitForSeconds(1f);}
yield return null;}}}
have two questions, one how would I be able to incorporate a keyboard input so the coroutine only start when it gets an input from keyboard and not upon entering play mode.
2.two, As you see on my code once the loop has gone throgh all the objects it will have them be removed but I want it once the loop is over I want it to get all the audio sources again and loop randomly as previous when getting input from keyboard
Answer by Filhanteraren · Jun 21, 2017 at 02:33 AM
To get any input use this in your update method:
if (Input.GetKeyDown(KeyCode.Space))
{
// Do something here;
}
}
You can read more about it in the documentation here:
https://docs.unity3d.com/Manual/Input.html
For your second question you could use another list to go through your indexes. And remove and reset that list when you are done.
I made a quick script here bellow that should work, not tested so be aware of that.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayRandomSound : MonoBehaviour
{
public List<AudioSource> sourcesInScene; //assign these in the inspector
private List<int> indexCount = new List<int>();
public void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
ResetIndexCount(sourcesInScene.Count);
StartCoroutine(SoundsTick());
}
}
private void ResetIndexCount(int number)
{
indexCount.Clear();
for (int i = 0; i < number; i++)
{
indexCount.Add(i);
}
}
IEnumerator SoundsTick()
{
//we're using an ienumerator so we can "wait" between loops.
while (indexCount.Count != 0)
{
for (int x = 0; x < sourcesInScene.Count; x++)
{
var i = Random.Range(0, indexCount.Count);
sourcesInScene[indexCount[i]].Play();
indexCount.RemoveAt(i);
yield return new WaitForSeconds(1f);
}
yield return null;
}
}
}