74 lines
1.5 KiB
C#
Raw Permalink Normal View History

2024-02-19 21:00:36 +03:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
public class Radio : NetworkBehaviour
{
[SyncVar(hook = nameof(OnStateChanged))]
public bool state = true;
[SyncVar(hook = nameof(OnTimeChanged))]
public double startTime;
public AudioSource audioSource;
public List<AudioClip> clipList;
public double time;
private IEnumerator _stopCoroutine;
public void Interact()
{
CmdInteract();
}
[Command(requiresAuthority = false)]
private void CmdInteract(NetworkConnectionToClient sender = null)
{
state = !state;
startTime = !state ? NetworkTime.time : -1f;
_stopCoroutine = StopTrack();
if (state)
{
StartCoroutine(_stopCoroutine);
}
else
{
StopCoroutine(_stopCoroutine);
}
}
private IEnumerator StopTrack()
{
yield return new WaitForSeconds(audioSource.clip.length);
state = false;
startTime = -1f;
}
void OnStateChanged(bool oldState, bool newState)
{
audioSource.PlayOneShot(Resources.Load<AudioClip>("Audio/ButtonSounds/button1"));
}
void OnTimeChanged(double oldValue, double newValue)
{
if (newValue >= 0f)
{
audioSource.Play();
audioSource.time = (float)(NetworkTime.time - newValue);
}
else
{
audioSource.Stop();
}
}
}