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

public class LaundryMachine : MonoBehaviour
{
    public AudioSource machineSound;
    public AudioClip[] runningSounds = new AudioClip[4];
    private AudioClip runningSound;
    public AudioClip buttonPressSound;
    public GameObject statusLight;
    public Material redLight, greenLight, offLight;
    private bool playerInBounds;
    private bool machineRunning;
    private GameObject interactionUI;

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

    private void Awake()
    {
        int randomClip = Random.Range(0, 4);
        runningSound = runningSounds[randomClip];
        interactionUI = GameObject.Find("Interaction Text");
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.E) && playerInBounds)
        {
            if (machineRunning)
                StopMachine();
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        playerInBounds = true;

        if (machineRunning)
            interactionUI.SetActive(true);
    }

    private void OnTriggerExit(Collider other)
    {
        playerInBounds = false;

        interactionUI.SetActive(false);
    }

    public void RunMachine()
    {
        //play a clip
        if (transform.parent.gameObject.activeSelf)
        {
            machineSound.clip = runningSound;
            machineSound.loop = true;
            machineSound.Play();
            //turn the machine light to red
            statusLight.GetComponent<MeshRenderer>().material = redLight;
            machineRunning = true;
        }

    }

    public void StopMachine()
    {
        //stop the audio
        if (transform.parent.gameObject.activeSelf)
        {
            machineSound.clip = buttonPressSound;
            machineSound.loop = false;
            machineSound.Play();
            //turn the machine light to green
            statusLight.GetComponent<MeshRenderer>().material = greenLight;
            machineRunning = false;
            interactionUI.SetActive(false);
        }
    }

    public void TurnOffMachine()
    {
        machineSound.Stop();
        statusLight.GetComponent<MeshRenderer>().material = offLight;
        machineRunning = false;
    }

    public void TurnOnMachine()
    {
        statusLight.GetComponent<MeshRenderer>().material = greenLight;
    }

    public void ResetMachine()
    {
        //turn off the machine when the player pushes the physical button
        StopMachine();
    }
}