UnityGameProjectsCode / NightwatchGame / VendingMachine.cs
VendingMachine.cs
Raw
using UnityEngine;

public class VendingMachine : MonoBehaviour
{
    private AudioSource machineAudio;
    public GameObject frontGlass;
    public Material glassOffMat, glassOnMat;
    public AudioClip startUpSound, runningSound;
    public InteractionTextControl textControl;
    public GameObject interactionUI;
    public Light machineGlow;
    private float startUpSoundTime = 3f;
    private float timeSinceStartup = 0.0f;
    private bool machineRunning;
    private bool playerNearby;

    public bool MachineRunning { get => machineRunning; set => machineRunning = value; }

    private void Awake()
    {
        machineAudio = GetComponent<AudioSource>();
    }

    private void OnTriggerEnter(Collider other)
    {
        playerNearby = true;
        interactionUI.SetActive(true);
    }

    private void OnTriggerExit(Collider other)
    {
        playerNearby = false;
        interactionUI.SetActive(false);
    }

    private void Update()
    {
        if (machineAudio.clip == startUpSound && machineRunning)
        {
            timeSinceStartup += Time.deltaTime;

            if (timeSinceStartup >= startUpSoundTime)
            {
                machineAudio.clip = runningSound;
                machineAudio.loop = true;
                machineAudio.pitch = 0.3f;
                machineAudio.volume = 0.3f;
                machineAudio.maxDistance = 15;
                machineAudio.Play();
            }
        }

        if (playerNearby && Input.GetKeyDown(KeyCode.E) && !machineRunning)
        {
            textControl.DisplayText("Broke last week.");
        }

        if (playerNearby && Input.GetKeyDown(KeyCode.E) && machineRunning)
        {
            textControl.DisplayText("This was broken...");
        }
    }

    public void StartMachine()
    {
        //play the startup sound and then switch to a running sound
        //turn on the front of the machine by making it glow
        machineAudio.clip = startUpSound;
        machineAudio.loop = false;
        machineAudio.pitch = 0.8f;
        machineAudio.volume = 1;
        machineAudio.Play();
        frontGlass.GetComponent<MeshRenderer>().material = glassOnMat;
        machineGlow.enabled = true;
        machineRunning = true;
    }

    public void TurnOffMachine()
    {
        //stop sounds and glow
        machineAudio.Stop();
        frontGlass.GetComponent<MeshRenderer>().material = glassOffMat;
        machineGlow.enabled = false;
        machineRunning = false;
    }
}