- Home /
How Do I Get This To Play Sound?
Hi, I'm fairly new to programming and I need help. I've been trying to make it so audio plays when you press the "start conversation" button and when the program writes a letter. However, it just doesn't seem to work. Please help me rewrite my spaghetti code and solve this issue. Help is much appreciated :)
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using UnityEngine.UI; using System.Threading; using System.Linq; using UnityEngine.UIElements; using UnityEditor.Audio; using UnityEngine.Audio; using System; using Random = UnityEngine.Random;
public class CubeScript : MonoBehaviour { public Queue sentences; public Animator animator; public TextMeshProUGUI Text; [TextArea(3, 10)] public string[] Sentences; public AudioClip[] sounds; public AudioSource audioSource;
private void Start()
{
sentences = new Queue<string>();
sentences.Clear();
foreach (string sentence in Sentences)
{
sentences.Enqueue(sentence);
}
DisplayNextSentence();
}
private void FixedUpdate()
{
if (Input.GetKeyDown(KeyCode.Space))
{
DisplayNextSentence();
}
}
public void DisplayNextSentence()
{
if (sentences.Count == 0)
{
EndDialogue();
return;
}
string sentence = sentences.Dequeue();
StartCoroutine(TypeText(sentence));
}
public void EndDialogue()
{
Text.text = "(End of conversation)";
}
public void StartConvo()
{
animator.SetTrigger("DialogueStarted");
PlayAudio();
}
IEnumerator TypeText(string sentence)
{
Text.text = "";
foreach (char letter in sentence.ToCharArray())
{
if (letter == '.')
{
Text.text += letter;
PlayAudio();
yield return new WaitForSeconds(0.5f);
}
else
{
Text.text += letter;
PlayAudio();
yield return new WaitForSeconds(0.1f);
}
}
}
private void PlayAudio()
{
audioSource.clip = sounds[Random.Range(0, sounds.Length)];
audioSource.PlayOneShot(audioSource.clip);
}
}