UnityGameProjectsCode / NightwatchGame / PlayClipRandomTime.cs
PlayClipRandomTime.cs
Raw
using System.Collections.Generic;
using UnityEngine;

public class PlayClipRandomTime : MonoBehaviour
{
    public List<Transform> allMarkers = new List<Transform>();
    public List<AudioClip> allClips = new List<AudioClip>();
    private Transform lastMarker, currentMarker;
    private AudioSource memeSound;
    private AudioClip lastClip, currentClip;
    public float baseWaitTime;
    private float modifiedWaitTime;
    private float timeWaited;
    private bool soundPlayed;


    private void Awake()
    {
        memeSound = GetComponent<AudioSource>();
        currentMarker = allMarkers[1];
        lastMarker = allMarkers[0];

        ChooseRandomPosition();
    }

    private void Update()
    {
        if (!memeSound.isPlaying && soundPlayed)
        {
            timeWaited += Time.deltaTime;

            if (timeWaited >= modifiedWaitTime)
            {
                ChooseRandomPosition();
                timeWaited = 0.0f;
            }

        }
    }

    private void ChooseRandomPosition()
    {
        Vector3 newPosition;
        AudioClip newSound;
        int randomMarker;
        int randomSound;

        do
        {
            randomMarker = Random.Range(0, allMarkers.Count);

            newPosition = allMarkers[randomMarker].position;
        }
        while (newPosition == currentMarker.position || newPosition == lastMarker.position);

        do
        {
            randomSound = Random.Range(0, allClips.Count);

            newSound = allClips[randomSound];
        }
        while (newSound == currentClip || newSound == lastClip);

        lastMarker = currentMarker;
        currentMarker = allMarkers[randomMarker];

        lastClip = currentClip;
        currentClip = allClips[randomSound];

        soundPlayed = false;

        MoveToNewPosition();
    }

    private void MoveToNewPosition()
    {
        memeSound.gameObject.transform.position = currentMarker.position;
        memeSound.clip = currentClip;
        memeSound.pitch = Random.Range(0.9f, 1.1f);
        memeSound.volume = Random.Range(0.015f, 0.15f);
        modifiedWaitTime = baseWaitTime + Random.Range(0, 3);
        memeSound.Play();
        soundPlayed = true;
    }
}