Question by
HalBar_Wick · Nov 24, 2020 at 06:37 PM ·
audiofunctions
Issue with calling functions in order
This script is intended to play an audio clip when the spacebar is pressed, with branching options for different clips with each subsequent press. The variable currentTrack was intended to gatekeep off certain functions until the right time, however - at the moment, it's skipping over Track1() on first pressing the spacebar, instead playing Audio clip clip2a. Any advice would be greatly appreciated, and apologies for my very amateurish code.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
public class AudioScore : MonoBehaviour
{
private AudioSource audioSource;
private AudioClip clip1a;
private AudioClip clip2a;
private AudioClip clip2b;
private int currentTrack = 0;
private float timerAudio;
private bool timerActive = false;
void Awake()
{
audioSource = gameObject.GetComponent<AudioSource>();
clip1a = Resources.Load<AudioClip>("Audio/1a");
clip2a = Resources.Load<AudioClip>("Audio/2a");
clip2b = Resources.Load<AudioClip>("Audio/2b");
}
void Update()
{
SpacebarPress(ref currentTrack);
TimerSet(ref timerActive);
Debug.Log(timerAudio);
}
//General timer, able to be started/reset by Bool timerActive
void TimerSet(ref bool timerActive)
{
if (timerActive == true)
{
timerAudio += Time.deltaTime;
}
if ((timerActive == false) && (timerAudio > 0))
{
timerAudio = 0;
timerActive = true;
}
}
void SpacebarPress(ref int currentTrack)
{
if (Input.GetKeyDown("space"))
{
if (currentTrack == 0)
{
Track1(ref currentTrack);
}
if (currentTrack == 1)
{
Track2(ref currentTrack);
}
}
}
void Track1(ref int currentTrack)
{
audioSource.clip = clip1a;
audioSource.Play();
currentTrack = 1;
timerActive = true;
}
void Track2(ref int currentTrack)
{
if (timerAudio < 0.5)
{
audioSource.clip = clip2a;
audioSource.Play();
currentTrack = 2;
timerActive = false;
}
else if (timerAudio > 0.5)
{
audioSource.clip = clip2b;
audioSource.Play();
currentTrack = 3;
timerActive = false;
}
}
}
Comment
Your answer
