non-vr lobby, version fix

This commit is contained in:
joonasp
2022-06-29 14:45:17 +03:00
parent 5774be9822
commit 04baadfad1
1774 changed files with 573069 additions and 1533 deletions

View File

@@ -0,0 +1,34 @@
namespace Photon.Voice.Unity.Demos
{
using UnityEngine;
using UnityEngine.UI;
public class BackgroundMusicController : MonoBehaviour
{
#pragma warning disable 649
[SerializeField]
private Text volumeText;
[SerializeField]
private Slider volumeSlider;
[SerializeField]
private AudioSource audioSource;
[SerializeField]
private float initialVolume = 0.125f;
#pragma warning restore 649
private void Awake()
{
this.volumeSlider.minValue = 0f;
this.volumeSlider.maxValue = 1f;
this.volumeSlider.SetSingleOnValueChangedCallback(this.OnVolumeChanged);
this.volumeSlider.value = this.initialVolume;
this.OnVolumeChanged(this.initialVolume);
}
private void OnVolumeChanged(float newValue)
{
this.volumeText.text = string.Format("BG Volume: {0:0.###}", newValue);
this.audioSource.volume = newValue;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: aec32561f997fa94cb5db680ffee8c5e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,194 @@
namespace Photon.Voice.Unity.Demos.DemoVoiceUI
{
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using POpusCodec.Enums;
public class CodecSettingsUI : MonoBehaviour
{
#pragma warning disable 649
[SerializeField]
private Dropdown frameDurationDropdown;
[SerializeField]
private Dropdown samplingRateDropdown;
[SerializeField]
private InputField bitrateInputField;
[SerializeField]
private Recorder recorder;
#pragma warning restore 649
private static readonly List<string> frameDurationOptions = new List<string>
{
"2.5ms", // EnumValueToString(OpusCodec.FrameDuration.Frame2dot5ms),
"5ms", // EnumValueToString(OpusCodec.FrameDuration.Frame5ms),
"10ms", // EnumValueToString(OpusCodec.FrameDuration.Frame10ms),
"20ms", // EnumValueToString( OpusCodec.FrameDuration.Frame20ms),
"40ms", // EnumValueToString(OpusCodec.FrameDuration.Frame40ms),
"60ms" // EnumValueToString(OpusCodec.FrameDuration.Frame60ms)
};
private static readonly List<string> samplingRateOptions = new List<string>
{
"8kHz", // EnumValueToString(SamplingRate.Sampling08000),
"12kHz", // EnumValueToString(SamplingRate.Sampling12000),
"16kHz", // EnumValueToString(SamplingRate.Sampling16000),
"24kHz", // EnumValueToString(SamplingRate.Sampling24000),
"48kHz", // EnumValueToString(SamplingRate.Sampling48000)
};
private void Awake()
{
this.frameDurationDropdown.ClearOptions();
this.frameDurationDropdown.AddOptions(frameDurationOptions);
this.InitFrameDuration();
this.frameDurationDropdown.SetSingleOnValueChangedCallback(this.OnFrameDurationChanged);
this.samplingRateDropdown.ClearOptions();
this.samplingRateDropdown.AddOptions(samplingRateOptions);
this.InitSamplingRate();
this.samplingRateDropdown.SetSingleOnValueChangedCallback(this.OnSamplingRateChanged);
this.bitrateInputField.SetSingleOnValueChangedCallback(this.OnBitrateChanged);
this.InitBitrate();
}
#region UNITY_EDITOR
private void Update()
{
this.InitFrameDuration();
this.InitSamplingRate();
this.InitBitrate();
}
#endregion
private void OnBitrateChanged(string newBitrateString)
{
int newBirate;
if (int.TryParse(newBitrateString, out newBirate))
{
this.recorder.Bitrate = newBirate;
if (this.recorder.RequiresRestart)
{
this.recorder.RestartRecording();
}
}
}
private void OnFrameDurationChanged(int index)
{
OpusCodec.FrameDuration newFrameDuration = this.recorder.FrameDuration;
switch (index)
{
case 0:
newFrameDuration = OpusCodec.FrameDuration.Frame2dot5ms;
break;
case 1:
newFrameDuration = OpusCodec.FrameDuration.Frame5ms;
break;
case 2:
newFrameDuration = OpusCodec.FrameDuration.Frame10ms;
break;
case 3:
newFrameDuration = OpusCodec.FrameDuration.Frame20ms;
break;
case 4:
newFrameDuration = OpusCodec.FrameDuration.Frame40ms;
break;
case 5:
newFrameDuration = OpusCodec.FrameDuration.Frame60ms;
break;
}
this.recorder.FrameDuration = newFrameDuration;
if (this.recorder.RequiresRestart)
{
this.recorder.RestartRecording();
}
}
private void OnSamplingRateChanged(int index)
{
SamplingRate newSamplingRate = this.recorder.SamplingRate;
switch (index)
{
case 0:
newSamplingRate = SamplingRate.Sampling08000;
break;
case 1:
newSamplingRate = SamplingRate.Sampling12000;
break;
case 2:
newSamplingRate = SamplingRate.Sampling16000;
break;
case 3:
newSamplingRate = SamplingRate.Sampling24000;
break;
case 4:
newSamplingRate = SamplingRate.Sampling48000;
break;
}
this.recorder.SamplingRate = newSamplingRate;
if (this.recorder.RequiresRestart)
{
this.recorder.RestartRecording();
}
}
private void InitFrameDuration()
{
int index = 0;
switch (this.recorder.FrameDuration)
{
case OpusCodec.FrameDuration.Frame5ms:
index = 1;
break;
case OpusCodec.FrameDuration.Frame10ms:
index = 2;
break;
case OpusCodec.FrameDuration.Frame20ms:
index = 3;
break;
case OpusCodec.FrameDuration.Frame40ms:
index = 4;
break;
case OpusCodec.FrameDuration.Frame60ms:
index = 5;
break;
}
this.frameDurationDropdown.value = index;
}
private void InitSamplingRate()
{
int index = 0;
switch (this.recorder.SamplingRate)
{
case SamplingRate.Sampling12000:
index = 1;
break;
case SamplingRate.Sampling16000:
index = 2;
break;
case SamplingRate.Sampling24000:
index = 3;
break;
case SamplingRate.Sampling48000:
index = 4;
break;
}
this.samplingRateDropdown.value = index;
}
private void InitBitrate()
{
this.bitrateInputField.text = this.recorder.Bitrate.ToString();
}
//private static string EnumValueToString(object enumValue)
//{
// return Enum.GetName(enumValue.GetType(), enumValue);
//}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 28f4b5ea592c07a46923a0bda48b14b1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,667 @@
#if UNITY_EDITOR_WIN || UNITY_EDITOR_OSX || !UNITY_EDITOR && (UNITY_IOS || UNITY_ANDROID || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX)
#define WEBRTC_AUDIO_DSP_SUPPORTED
#endif
namespace Photon.Voice.Unity.Demos.DemoVoiceUI
{
using System.Collections.Generic;
using Realtime;
using ExitGames.Client.Photon;
using UtilityScripts;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(VoiceConnection), typeof(ConnectAndJoin))]
public class DemoVoiceUI : MonoBehaviour, IInRoomCallbacks, IMatchmakingCallbacks
{
#pragma warning disable 649
[SerializeField]
private Text connectionStatusText;
[SerializeField]
private Text serverStatusText;
[SerializeField]
private Text roomStatusText;
[SerializeField]
private Text inputWarningText;
[SerializeField]
private Text rttText;
[SerializeField]
private Text rttVariationText;
[SerializeField]
private Text packetLossWarningText;
[SerializeField]
private InputField localNicknameText;
[SerializeField]
private Toggle debugEchoToggle;
[SerializeField]
private Toggle reliableTransmissionToggle;
[SerializeField]
private Toggle encryptionToggle;
[SerializeField]
private GameObject webRtcDspGameObject;
[SerializeField]
private Toggle aecToggle;
[SerializeField]
private Toggle aecHighPassToggle;
[SerializeField]
private InputField reverseStreamDelayInputField;
[SerializeField]
private Toggle noiseSuppressionToggle;
[SerializeField]
private Toggle agcToggle;
[SerializeField]
private Slider agcCompressionGainSlider;
[SerializeField]
private Toggle vadToggle;
[SerializeField]
private Toggle muteToggle;
[SerializeField]
private Toggle streamAudioClipToggle;
[SerializeField]
private Toggle audioToneToggle;
[SerializeField]
private Toggle dspToggle;
[SerializeField]
private Toggle highPassToggle;
[SerializeField]
private Toggle photonVadToggle;
[SerializeField]
private GameObject microphoneSetupGameObject;
[SerializeField]
private bool defaultTransmitEnabled = false;
[SerializeField]
private int screenWidth = 800;
[SerializeField]
private int screenHeight = 600;
[SerializeField]
private bool fullScreen;
[SerializeField]
private InputField roomNameInputField;
[SerializeField]
private InputField globalMinDelaySoftInputField;
[SerializeField]
private InputField globalMaxDelaySoftInputField;
[SerializeField]
private InputField globalMaxDelayHardInputField;
[SerializeField]
private int rttYellowThreshold = 100;
[SerializeField]
private int rttRedThreshold = 160;
[SerializeField]
private int rttVariationYellowThreshold = 25;
[SerializeField]
private int rttVariationRedThreshold = 50;
#pragma warning restore 649
private GameObject compressionGainGameObject;
private Text compressionGainText;
private GameObject aecOptionsGameObject;
public Transform RemoteVoicesPanel;
protected VoiceConnection voiceConnection;
private WebRtcAudioDsp voiceAudioPreprocessor;
private ConnectAndJoin connectAndJoin;
private readonly Color warningColor = new Color(0.9f,0.5f,0f,1f);
private readonly Color okColor = new Color(0.0f,0.6f,0.2f,1f);
private readonly Color redColor = new Color(1.0f,0.0f,0.0f,1f);
private readonly Color defaultColor = new Color(0.0f,0.0f,0.0f,1f);
private void Awake()
{
Screen.SetResolution(this.screenWidth, this.screenHeight, this.fullScreen);
this.connectAndJoin = this.GetComponent<ConnectAndJoin>();
this.voiceConnection = this.GetComponent<VoiceConnection>();
this.voiceAudioPreprocessor = this.voiceConnection.PrimaryRecorder.GetComponent<WebRtcAudioDsp>();
this.compressionGainGameObject = this.agcCompressionGainSlider.transform.parent.gameObject;
this.compressionGainText = this.compressionGainGameObject.GetComponentInChildren<Text>();
this.aecOptionsGameObject = this.aecHighPassToggle.transform.parent.gameObject;
this.SetDefaults();
this.InitUiCallbacks();
this.InitUiValues();
this.GetSavedNickname();
}
protected virtual void SetDefaults()
{
this.muteToggle.isOn = !this.defaultTransmitEnabled;
}
private void OnEnable()
{
this.voiceConnection.SpeakerLinked += this.OnSpeakerCreated;
this.voiceConnection.Client.AddCallbackTarget(this);
}
private void OnDisable()
{
this.voiceConnection.SpeakerLinked -= this.OnSpeakerCreated;
this.voiceConnection.Client.RemoveCallbackTarget(this);
}
private void GetSavedNickname()
{
string savedNick = PlayerPrefs.GetString("vNick");
if (!string.IsNullOrEmpty(savedNick))
{
//Debug.LogFormat("Saved nick = {0}", savedNick);
this.localNicknameText.text = savedNick;
this.voiceConnection.Client.NickName = savedNick;
}
}
protected virtual void OnSpeakerCreated(Speaker speaker)
{
speaker.gameObject.transform.SetParent(this.RemoteVoicesPanel, false);
RemoteSpeakerUI remoteSpeakerUi = speaker.GetComponent<RemoteSpeakerUI>();
remoteSpeakerUi.Init(this.voiceConnection);
speaker.OnRemoteVoiceRemoveAction += this.OnRemoteVoiceRemove;
}
private void OnRemoteVoiceRemove(Speaker speaker)
{
if (speaker != null)
{
Destroy(speaker.gameObject);
}
}
private void ToggleMute(bool isOn) // transmit is used as opposite of mute...
{
this.muteToggle.targetGraphic.enabled = !isOn;
if (isOn)
{
this.voiceConnection.Client.LocalPlayer.Mute();
}
else
{
this.voiceConnection.Client.LocalPlayer.Unmute();
}
}
protected virtual void ToggleIsRecording(bool isRecording)
{
this.voiceConnection.PrimaryRecorder.IsRecording = isRecording;
}
private void ToggleDebugEcho(bool isOn)
{
this.voiceConnection.PrimaryRecorder.DebugEchoMode = isOn;
}
private void ToggleReliable(bool isOn)
{
this.voiceConnection.PrimaryRecorder.ReliableMode = isOn;
}
private void ToggleEncryption(bool isOn)
{
this.voiceConnection.PrimaryRecorder.Encrypt = isOn;
}
private void ToggleAEC(bool isOn)
{
this.voiceAudioPreprocessor.AEC = isOn;
this.aecOptionsGameObject.SetActive(isOn);
}
private void ToggleNoiseSuppression(bool isOn)
{
this.voiceAudioPreprocessor.NoiseSuppression = isOn;
}
private void ToggleAGC(bool isOn)
{
this.voiceAudioPreprocessor.AGC = isOn;
this.compressionGainGameObject.SetActive(isOn);
}
private void ToggleVAD(bool isOn)
{
this.voiceAudioPreprocessor.VAD = isOn;
}
private void ToggleHighPass(bool isOn)
{
this.voiceAudioPreprocessor.HighPass = isOn;
}
private void ToggleDsp(bool isOn)
{
this.voiceAudioPreprocessor.Bypass = !isOn;
this.voiceAudioPreprocessor.enabled = isOn;
this.webRtcDspGameObject.SetActive(isOn);
}
private void ToggleAudioClipStreaming(bool isOn)
{
this.microphoneSetupGameObject.SetActive(!isOn && !this.audioToneToggle.isOn);
if (isOn)
{
this.audioToneToggle.SetValue(false);
this.voiceConnection.PrimaryRecorder.SourceType = Recorder.InputSourceType.AudioClip;
}
else if (!this.audioToneToggle.isOn)
{
this.voiceConnection.PrimaryRecorder.SourceType = Recorder.InputSourceType.Microphone;
}
if (this.voiceConnection.PrimaryRecorder.RequiresRestart)
{
this.voiceConnection.PrimaryRecorder.RestartRecording();
}
}
private void ToggleAudioToneFactory(bool isOn)
{
this.microphoneSetupGameObject.SetActive(!isOn && !this.streamAudioClipToggle.isOn);
if (isOn)
{
this.streamAudioClipToggle.SetValue(false);
this.dspToggle.isOn = false;
this.voiceConnection.PrimaryRecorder.InputFactory = () => new AudioUtil.ToneAudioReader<float>();
this.voiceConnection.PrimaryRecorder.SourceType = Recorder.InputSourceType.Factory;
}
else if (!this.streamAudioClipToggle.isOn)
{
this.voiceConnection.PrimaryRecorder.SourceType = Recorder.InputSourceType.Microphone;
}
if (this.voiceConnection.PrimaryRecorder.RequiresRestart)
{
this.voiceConnection.PrimaryRecorder.RestartRecording();
}
}
private void TogglePhotonVAD(bool isOn)
{
this.voiceConnection.PrimaryRecorder.VoiceDetection = isOn;
}
private void ToggleAecHighPass(bool isOn)
{
this.voiceAudioPreprocessor.AecHighPass = isOn;
}
private void OnAgcCompressionGainChanged(float agcCompressionGain)
{
this.voiceAudioPreprocessor.AgcCompressionGain = (int)agcCompressionGain;
this.compressionGainText.text = string.Concat("Compression Gain: ", agcCompressionGain);
}
private void OnGlobalPlaybackDelayMinSoftChanged(string newMinDelaySoftString)
{
int newMinDelaySoftValue;
int newMaxDelaySoftValue = this.voiceConnection.GlobalPlaybackDelayMaxSoft;
int newMaxDelayHardValue = this.voiceConnection.GlobalPlaybackDelayMaxHard;
if (int.TryParse(newMinDelaySoftString, out newMinDelaySoftValue) && newMinDelaySoftValue >= 0 && newMinDelaySoftValue < newMaxDelaySoftValue)
{
this.voiceConnection.SetGlobalPlaybackDelaySettings(newMinDelaySoftValue, newMaxDelaySoftValue, newMaxDelayHardValue);
}
else
{
this.globalMinDelaySoftInputField.text = this.voiceConnection.GlobalPlaybackDelayMinSoft.ToString();
}
}
private void OnGlobalPlaybackDelayMaxSoftChanged(string newMaxDelaySoftString)
{
int newMinDelaySoftValue = this.voiceConnection.GlobalPlaybackDelayMinSoft;
int newMaxDelaySoftValue;
int newMaxDelayHardValue = this.voiceConnection.GlobalPlaybackDelayMaxHard;
if (int.TryParse(newMaxDelaySoftString, out newMaxDelaySoftValue) && newMaxDelaySoftValue > newMinDelaySoftValue)
{
this.voiceConnection.SetGlobalPlaybackDelaySettings(newMinDelaySoftValue, newMaxDelaySoftValue, newMaxDelayHardValue);
}
else
{
this.globalMaxDelaySoftInputField.text = this.voiceConnection.GlobalPlaybackDelayMaxSoft.ToString();
}
}
private void OnGlobalPlaybackDelayMaxHardChanged(string newMaxDelayHardString)
{
int newMinDelaySoftValue = this.voiceConnection.GlobalPlaybackDelayMinSoft;
int newMaxDelaySoftValue = this.voiceConnection.GlobalPlaybackDelayMaxSoft;
int newMaxDelayHardValue;
if (int.TryParse(newMaxDelayHardString, out newMaxDelayHardValue) && newMaxDelayHardValue >= newMaxDelaySoftValue)
{
this.voiceConnection.SetGlobalPlaybackDelaySettings(newMinDelaySoftValue, newMaxDelaySoftValue, newMaxDelayHardValue);
}
else
{
this.globalMaxDelayHardInputField.text = this.voiceConnection.GlobalPlaybackDelayMaxHard.ToString();
}
}
private void OnReverseStreamDelayChanged(string newReverseStreamString)
{
int newReverseStreamValue;
if (int.TryParse(newReverseStreamString, out newReverseStreamValue) && newReverseStreamValue > 0)
{
this.voiceAudioPreprocessor.ReverseStreamDelayMs = newReverseStreamValue;
}
else
{
this.reverseStreamDelayInputField.text = this.voiceAudioPreprocessor.ReverseStreamDelayMs.ToString();
}
}
private void UpdateSyncedNickname(string nickname)
{
nickname = nickname.Trim();
if (string.IsNullOrEmpty(nickname))
{
return;
}
//Debug.LogFormat("UpdateSyncedNickname() name: {0}", nickname);
this.voiceConnection.Client.LocalPlayer.NickName = nickname;
PlayerPrefs.SetString("vNick", nickname);
}
private void JoinOrCreateRoom(string roomName)
{
if (string.IsNullOrEmpty(roomName))
{
this.connectAndJoin.RoomName = string.Empty;
this.connectAndJoin.RandomRoom = true;
}
else
{
this.connectAndJoin.RoomName = roomName.Trim();
this.connectAndJoin.RandomRoom = false;
}
if (this.voiceConnection.Client.InRoom)
{
this.voiceConnection.Client.OpLeaveRoom(false);
}
else if (!this.voiceConnection.Client.IsConnected)
{
this.voiceConnection.ConnectUsingSettings();
}
}
protected virtual void Update()
{
#if UNITY_EDITOR
this.InitUiValues(); // refresh UI in case changed from Unity Editor
#endif
this.connectionStatusText.text = this.voiceConnection.Client.State.ToString();
this.serverStatusText.text = string.Format("{0}/{1}", this.voiceConnection.Client.CloudRegion, this.voiceConnection.Client.CurrentServerAddress);
if (this.voiceConnection.PrimaryRecorder.IsCurrentlyTransmitting)
{
var amplitude = this.voiceConnection.PrimaryRecorder.LevelMeter.CurrentAvgAmp;
if (amplitude > 1)
{
amplitude /= (short.MaxValue + 1);
}
if (amplitude > 0.1)
{
this.inputWarningText.text = "Input too loud!";
this.inputWarningText.color = this.warningColor;
}
else
{
this.inputWarningText.text = string.Empty;
this.ResetTextColor(this.inputWarningText);
}
}
if (this.voiceConnection.FramesReceivedPerSecond > 0)
{
this.packetLossWarningText.text = string.Format("{0:0.##}% Packet Loss", this.voiceConnection.FramesLostPercent);
this.packetLossWarningText.color = this.voiceConnection.FramesLostPercent > 1 ? this.warningColor : this.okColor;
}
else
{
this.packetLossWarningText.text = string.Empty;
this.ResetTextColor(this.packetLossWarningText);
}
this.rttText.text = string.Concat("RTT:", this.voiceConnection.Client.LoadBalancingPeer.RoundTripTime);
this.SetTextColor(this.voiceConnection.Client.LoadBalancingPeer.RoundTripTime, this.rttText, this.rttYellowThreshold, this.rttRedThreshold);
this.rttVariationText.text = string.Concat("VAR:", this.voiceConnection.Client.LoadBalancingPeer.RoundTripTimeVariance);
this.SetTextColor(this.voiceConnection.Client.LoadBalancingPeer.RoundTripTimeVariance, this.rttVariationText, this.rttVariationYellowThreshold, this.rttVariationRedThreshold);
}
private void SetTextColor(int textValue, Text text, int yellowThreshold, int redThreshold)
{
if (textValue > redThreshold)
{
text.color = this.redColor;
}
else if (textValue > yellowThreshold)
{
text.color = this.warningColor;
}
else
{
text.color = this.okColor;
}
}
private void ResetTextColor(Text text)
{
text.color = this.defaultColor;
}
private void InitUiCallbacks()
{
this.muteToggle.SetSingleOnValueChangedCallback(this.ToggleMute);
this.debugEchoToggle.SetSingleOnValueChangedCallback(this.ToggleDebugEcho);
this.vadToggle.SetSingleOnValueChangedCallback(this.ToggleVAD);
this.aecToggle.SetSingleOnValueChangedCallback(this.ToggleAEC);
this.agcToggle.SetSingleOnValueChangedCallback(this.ToggleAGC);
this.debugEchoToggle.SetSingleOnValueChangedCallback(this.ToggleDebugEcho);
this.dspToggle.SetSingleOnValueChangedCallback(this.ToggleDsp);
this.highPassToggle.SetSingleOnValueChangedCallback(this.ToggleHighPass);
this.encryptionToggle.SetSingleOnValueChangedCallback(this.ToggleEncryption);
this.reliableTransmissionToggle.SetSingleOnValueChangedCallback(this.ToggleReliable);
this.streamAudioClipToggle.SetSingleOnValueChangedCallback(this.ToggleAudioClipStreaming);
this.photonVadToggle.SetSingleOnValueChangedCallback(this.TogglePhotonVAD);
this.aecHighPassToggle.SetSingleOnValueChangedCallback(this.ToggleAecHighPass);
this.noiseSuppressionToggle.SetSingleOnValueChangedCallback(this.ToggleNoiseSuppression);
this.audioToneToggle.SetSingleOnValueChangedCallback(this.ToggleAudioToneFactory);
this.agcCompressionGainSlider.SetSingleOnValueChangedCallback(this.OnAgcCompressionGainChanged);
this.localNicknameText.SetSingleOnEndEditCallback(this.UpdateSyncedNickname);
this.roomNameInputField.SetSingleOnEndEditCallback(this.JoinOrCreateRoom);
#if UNITY_EDITOR
this.globalMinDelaySoftInputField.SetSingleOnValueChangedCallback(this.OnGlobalPlaybackDelayMinSoftChanged);
this.globalMaxDelaySoftInputField.SetSingleOnValueChangedCallback(this.OnGlobalPlaybackDelayMaxSoftChanged);
this.globalMaxDelayHardInputField.SetSingleOnValueChangedCallback(this.OnGlobalPlaybackDelayMaxHardChanged);
this.reverseStreamDelayInputField.SetSingleOnValueChangedCallback(this.OnReverseStreamDelayChanged);
#else
this.globalMinDelaySoftInputField.SetSingleOnEndEditCallback(this.OnGlobalPlaybackDelayMinSoftChanged);
this.globalMaxDelaySoftInputField.SetSingleOnEndEditCallback(this.OnGlobalPlaybackDelayMaxSoftChanged);
this.globalMaxDelayHardInputField.SetSingleOnEndEditCallback(this.OnGlobalPlaybackDelayMaxHardChanged);
this.reverseStreamDelayInputField.SetSingleOnEndEditCallback(this.OnReverseStreamDelayChanged);
#endif
}
private void InitUiValues()
{
this.muteToggle.SetValue(this.voiceConnection.Client.LocalPlayer.IsMuted());
this.debugEchoToggle.SetValue(this.voiceConnection.PrimaryRecorder.DebugEchoMode);
this.reliableTransmissionToggle.SetValue(this.voiceConnection.PrimaryRecorder.ReliableMode);
this.encryptionToggle.SetValue(this.voiceConnection.PrimaryRecorder.Encrypt);
this.streamAudioClipToggle.SetValue(this.voiceConnection.PrimaryRecorder.SourceType ==
Recorder.InputSourceType.AudioClip);
this.audioToneToggle.SetValue(this.voiceConnection.PrimaryRecorder.SourceType == Recorder.InputSourceType.Factory);
this.microphoneSetupGameObject.SetActive(!this.streamAudioClipToggle.isOn && !this.audioToneToggle.isOn);
this.globalMinDelaySoftInputField.SetValue(this.voiceConnection.GlobalPlaybackDelayMinSoft.ToString());
this.globalMaxDelaySoftInputField.SetValue(this.voiceConnection.GlobalPlaybackDelayMaxSoft.ToString());
this.globalMaxDelayHardInputField.SetValue(this.voiceConnection.GlobalPlaybackDelayMaxHard.ToString());
if (this.webRtcDspGameObject != null)
{
#if WEBRTC_AUDIO_DSP_SUPPORTED
if (this.voiceAudioPreprocessor == null)
{
this.webRtcDspGameObject.SetActive(false);
this.dspToggle.gameObject.SetActive(false);
}
else
{
this.dspToggle.gameObject.SetActive(true);
this.dspToggle.SetValue(!this.voiceAudioPreprocessor.Bypass && this.voiceAudioPreprocessor.enabled);
this.webRtcDspGameObject.SetActive(this.dspToggle.isOn);
this.aecToggle.SetValue(this.voiceAudioPreprocessor.AEC);
this.aecHighPassToggle.SetValue(this.voiceAudioPreprocessor.AecHighPass);
this.reverseStreamDelayInputField.text = this.voiceAudioPreprocessor.ReverseStreamDelayMs.ToString();
this.aecOptionsGameObject.SetActive(this.voiceAudioPreprocessor.AEC);
this.noiseSuppressionToggle.isOn = this.voiceAudioPreprocessor.NoiseSuppression;
this.agcToggle.SetValue(this.voiceAudioPreprocessor.AGC);
this.agcCompressionGainSlider.SetValue(this.voiceAudioPreprocessor.AgcCompressionGain);
this.compressionGainGameObject.SetActive(this.voiceAudioPreprocessor.AGC);
this.vadToggle.SetValue(this.voiceAudioPreprocessor.VAD);
this.highPassToggle.SetValue(this.voiceAudioPreprocessor.HighPass);
}
#else
this.webRtcDspGameObject.SetActive(false);
this.dspToggle.gameObject.SetActive(false);
#endif
}
else
{
this.dspToggle.gameObject.SetActive(false);
}
}
private void SetRoomDebugText()
{
string playerDebugString = string.Empty;
if (this.voiceConnection.Client.InRoom)
{
foreach (Player p in this.voiceConnection.Client.CurrentRoom.Players.Values)
{
playerDebugString = string.Concat(playerDebugString, p.ToStringFull());
}
this.roomStatusText.text = string.Format("{0} {1}", this.voiceConnection.Client.CurrentRoom.Name, playerDebugString);
}
else
{
this.roomStatusText.text = string.Empty;
}
this.roomStatusText.text = this.voiceConnection.Client.CurrentRoom == null ? string.Empty : string.Format("{0} {1}", this.voiceConnection.Client.CurrentRoom.Name, playerDebugString);
}
protected virtual void OnActorPropertiesChanged(Player targetPlayer, Hashtable changedProps)
{
if (targetPlayer.IsLocal)
{
bool isMuted = targetPlayer.IsMuted();
this.voiceConnection.PrimaryRecorder.TransmitEnabled = !isMuted;
this.muteToggle.SetValue(isMuted);
}
this.SetRoomDebugText();
}
#region IInRoomCallbacks
void IInRoomCallbacks.OnPlayerEnteredRoom(Player newPlayer)
{
this.SetRoomDebugText();
}
void IInRoomCallbacks.OnPlayerLeftRoom(Player otherPlayer)
{
this.SetRoomDebugText();
}
void IInRoomCallbacks.OnRoomPropertiesUpdate(Hashtable propertiesThatChanged)
{
}
void IInRoomCallbacks.OnPlayerPropertiesUpdate(Player targetPlayer, Hashtable changedProps)
{
this.OnActorPropertiesChanged(targetPlayer, changedProps);
}
void IInRoomCallbacks.OnMasterClientSwitched(Player newMasterClient)
{
}
#endregion
#region IMatchmakingCallbacks
void IMatchmakingCallbacks.OnFriendListUpdate(List<FriendInfo> friendList)
{
}
void IMatchmakingCallbacks.OnCreatedRoom()
{
}
void IMatchmakingCallbacks.OnCreateRoomFailed(short returnCode, string message)
{
}
void IMatchmakingCallbacks.OnJoinedRoom()
{
this.SetRoomDebugText();
}
void IMatchmakingCallbacks.OnJoinRoomFailed(short returnCode, string message)
{
}
void IMatchmakingCallbacks.OnJoinRandomFailed(short returnCode, string message)
{
}
void IMatchmakingCallbacks.OnLeftRoom()
{
if (!ConnectionHandler.AppQuits)
{
this.SetRoomDebugText();
this.SetDefaults();
}
}
#endregion
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 094187b68c0de4668b10768c5945018a
timeCreated: 1530628279
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,279 @@
#if WINDOWS_UWP || ENABLE_WINMD_SUPPORT
#define PHOTON_MICROPHONE_WSA
#endif
#if PHOTON_MICROPHONE_WSA || UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN || UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX
#define PHOTON_MICROPHONE_ENUMERATOR
#endif
#if UNITY_STANDALONE_OSX || UNITY_STANDALONE_WIN || UNITY_ANDROID || UNITY_IOS || UNITY_WSA || UNITY_EDITOR_OSX || UNITY_EDITOR_WIN
#define PHOTON_MICROPHONE_SUPPORTED
#endif
namespace Photon.Voice.Unity.Demos.DemoVoiceUI
{
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Serialization;
using UnityEngine.UI;
public struct MicRef
{
public Recorder.MicType MicType;
public string Name;
public int PhotonId;
public string PhotonIdString;
public MicRef(string name, int id)
{
this.MicType = Recorder.MicType.Photon;
this.Name = name;
this.PhotonId = id;
this.PhotonIdString = string.Empty;
}
public MicRef(string name, string id)
{
this.MicType = Recorder.MicType.Photon;
this.Name = name;
this.PhotonId = -1;
this.PhotonIdString = id;
}
public MicRef(string name)
{
this.MicType = Recorder.MicType.Unity;
this.Name = name;
this.PhotonId = -1;
this.PhotonIdString = string.Empty;
}
public override string ToString()
{
return string.Format("Mic reference: {0}", this.Name);
}
}
public class MicrophoneDropdownFiller : MonoBehaviour
{
private List<MicRef> micOptions;
#pragma warning disable 649
[SerializeField]
private Dropdown micDropdown;
[SerializeField]
private Recorder recorder;
[SerializeField]
[FormerlySerializedAs("RefreshButton")]
private GameObject refreshButton;
[SerializeField]
[FormerlySerializedAs("ToggleButton")]
private GameObject toggleButton;
#pragma warning restore 649
private Toggle photonToggle;
private void Awake()
{
this.photonToggle = this.toggleButton.GetComponentInChildren<Toggle>();
this.RefreshMicrophones();
}
private void OnEnable()
{
UtilityScripts.MicrophonePermission.MicrophonePermissionCallback += this.OnMicrophonePermissionCallback;
}
private void OnMicrophonePermissionCallback(bool granted)
{
this.RefreshMicrophones();
}
private void OnDisable()
{
UtilityScripts.MicrophonePermission.MicrophonePermissionCallback -= this.OnMicrophonePermissionCallback;
}
private void SetupMicDropdown()
{
this.micDropdown.ClearOptions();
this.micOptions = new List<MicRef>();
List<string> micOptionsStrings = new List<string>();
for(int i=0; i < Microphone.devices.Length; i++)
{
string x = Microphone.devices[i];
this.micOptions.Add(new MicRef(x));
micOptionsStrings.Add(string.Format("[Unity] {0}", x));
}
#if PHOTON_MICROPHONE_ENUMERATOR
if (this.recorder.MicrophonesEnumerator.IsSupported)
{
int i = 0;
foreach (DeviceInfo deviceInfo in this.recorder.MicrophonesEnumerator)
{
string n = deviceInfo.Name;
#if PHOTON_MICROPHONE_WSA
this.micOptions.Add(new MicRef(n, deviceInfo.IDString));
#else
this.micOptions.Add(new MicRef(n, deviceInfo.IDInt));
#endif
micOptionsStrings.Add(string.Format("[Photon] {0}", n));
i++;
}
}
#endif
this.micDropdown.AddOptions(micOptionsStrings);
this.micDropdown.onValueChanged.RemoveAllListeners();
this.micDropdown.onValueChanged.AddListener(delegate { this.MicDropdownValueChanged(this.micOptions[this.micDropdown.value]); });
}
private void MicDropdownValueChanged(MicRef mic)
{
this.recorder.MicrophoneType = mic.MicType;
switch (mic.MicType)
{
case Recorder.MicType.Unity:
this.recorder.UnityMicrophoneDevice = mic.Name;
break;
case Recorder.MicType.Photon:
#if PHOTON_MICROPHONE_WSA
this.recorder.PhotonMicrophoneDeviceIdString = mic.PhotonIdString;
#else
this.recorder.PhotonMicrophoneDeviceId = mic.PhotonId;
#endif
break;
}
if (this.recorder.RequiresRestart)
{
this.recorder.RestartRecording();
}
}
private void SetCurrentValue()
{
if (this.micOptions == null)
{
Debug.LogWarning("micOptions list is null");
return;
}
#if PHOTON_MICROPHONE_ENUMERATOR
bool photonMicEnumAvailable = this.recorder.MicrophonesEnumerator.IsSupported;
#else
bool photonMicEnumAvailable = false;
#endif
this.photonToggle.onValueChanged.RemoveAllListeners();
this.photonToggle.isOn = this.recorder.MicrophoneType == Recorder.MicType.Photon;
if (!photonMicEnumAvailable)
{
this.photonToggle.onValueChanged.AddListener(this.PhotonMicToggled);
}
this.micDropdown.gameObject.SetActive(photonMicEnumAvailable || this.recorder.MicrophoneType == Recorder.MicType.Unity);
#if PHOTON_MICROPHONE_SUPPORTED
this.toggleButton.SetActive(!photonMicEnumAvailable);
#else
this.toggleButton.SetActive(false);
#endif
this.refreshButton.SetActive(photonMicEnumAvailable || this.recorder.MicrophoneType == Recorder.MicType.Unity);
for (int valueIndex = 0; valueIndex < this.micOptions.Count; valueIndex++)
{
MicRef val = this.micOptions[valueIndex];
if (this.recorder.MicrophoneType == val.MicType)
{
if (this.recorder.MicrophoneType == Recorder.MicType.Unity &&
Recorder.CompareUnityMicNames(val.Name, this.recorder.UnityMicrophoneDevice))
{
this.micDropdown.value = valueIndex;
return;
}
#if PHOTON_MICROPHONE_WSA
if (this.recorder.MicrophoneType == Recorder.MicType.Photon &&
string.Equals(val.PhotonIdString, this.recorder.PhotonMicrophoneDeviceIdString))
{
this.micDropdown.value = valueIndex;
return;
}
#else
if (this.recorder.MicrophoneType == Recorder.MicType.Photon &&
val.PhotonId == this.recorder.PhotonMicrophoneDeviceId)
{
this.micDropdown.value = valueIndex;
return;
}
#endif
}
}
for (int valueIndex = 0; valueIndex < this.micOptions.Count; valueIndex++)
{
MicRef val = this.micOptions[valueIndex];
if (this.recorder.MicrophoneType == val.MicType)
{
if (this.recorder.MicrophoneType == Recorder.MicType.Unity)
{
this.micDropdown.value = valueIndex;
this.recorder.UnityMicrophoneDevice = val.Name;
break;
}
if (this.recorder.MicrophoneType == Recorder.MicType.Photon)
{
this.micDropdown.value = valueIndex;
#if PHOTON_MICROPHONE_WSA
this.recorder.PhotonMicrophoneDeviceIdString = val.PhotonIdString;
#else
this.recorder.PhotonMicrophoneDeviceId = val.PhotonId;
#endif
break;
}
}
}
if (this.recorder.RequiresRestart)
{
this.recorder.RestartRecording();
}
}
public void PhotonMicToggled(bool on)
{
this.micDropdown.gameObject.SetActive(!on);
this.refreshButton.SetActive(!on);
if (on)
{
this.recorder.MicrophoneType = Recorder.MicType.Photon;
}
else
{
this.recorder.MicrophoneType = Recorder.MicType.Unity;
}
if (this.recorder.RequiresRestart)
{
this.recorder.RestartRecording();
}
}
public void RefreshMicrophones()
{
#if PHOTON_MICROPHONE_ENUMERATOR
//Debug.Log("Refresh Mics");
this.recorder.MicrophonesEnumerator.Refresh();
#endif
this.SetupMicDropdown();
this.SetCurrentValue();
}
// sync. UI in case a change happens from the Unity Editor Inspector
private void PhotonVoiceCreated()
{
this.RefreshMicrophones();
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 46c5b6e5ca0ea874f9e8d58fd90ef139
timeCreated: 1530628279
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,27 @@
namespace Photon.Voice.Unity.Demos.DemoVoiceUI
{
using Realtime;
using ExitGames.Client.Photon;
public static partial class PhotonDemoExtensions // todo: USE C.A.S. ALWAYS
{
// this demo uses a Custom Property (as explained in the Realtime API), to sync if a player muted her microphone. that value needs a string key.
internal const string IS_MUTED_PROPERTY_KEY = "mute";
public static bool Mute(this Player player)
{
return player.SetCustomProperties(new Hashtable(1) { { IS_MUTED_PROPERTY_KEY, true } });
}
public static bool Unmute(this Player player)
{
return player.SetCustomProperties(new Hashtable(1) { { IS_MUTED_PROPERTY_KEY, false } });
}
public static bool IsMuted(this Player player)
{
object temp;
return player.CustomProperties.TryGetValue(IS_MUTED_PROPERTY_KEY, out temp) && (bool)temp;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2f0b31909ac64a343906fc8be6490c2f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,171 @@
namespace Photon.Voice.Unity.Demos.DemoVoiceUI
{
using ExitGames.Client.Photon;
using Unity;
using UnityEngine;
using UnityEngine.UI;
using Realtime;
[RequireComponent(typeof(Speaker))]
public class RemoteSpeakerUI : MonoBehaviour, IInRoomCallbacks
{
#pragma warning disable 649
[SerializeField]
private Text nameText;
[SerializeField]
protected Image remoteIsMuting;
[SerializeField]
private Image remoteIsTalking;
[SerializeField]
private InputField minDelaySoftInputField;
[SerializeField]
private InputField maxDelaySoftInputField;
[SerializeField]
private InputField maxDelayHardInputField;
[SerializeField]
private Text bufferLagText;
#pragma warning restore 649
protected Speaker speaker;
protected VoiceConnection voiceConnection;
protected LoadBalancingClient loadBalancingClient;
protected virtual void Start()
{
this.speaker = this.GetComponent<Speaker>();
this.minDelaySoftInputField.text = this.speaker.PlaybackDelayMinSoft.ToString();
this.minDelaySoftInputField.SetSingleOnEndEditCallback(this.OnMinDelaySoftChanged);
this.maxDelaySoftInputField.text = this.speaker.PlaybackDelayMaxSoft.ToString();
this.maxDelaySoftInputField.SetSingleOnEndEditCallback(this.OnMaxDelaySoftChanged);
this.maxDelayHardInputField.text = this.speaker.PlaybackDelayMaxHard.ToString();
this.maxDelayHardInputField.SetSingleOnEndEditCallback(this.OnMaxDelayHardChanged);
this.SetNickname();
this.SetMutedState();
}
private void OnMinDelaySoftChanged(string newMinDelaySoftString)
{
int newMinDelaySoftValue;
int newMaxDelaySoftValue = this.speaker.PlaybackDelayMaxSoft;
int newMaxDelayHardValue = this.speaker.PlaybackDelayMaxHard;
if (int.TryParse(newMinDelaySoftString, out newMinDelaySoftValue) && newMinDelaySoftValue >= 0 && newMinDelaySoftValue < newMaxDelaySoftValue)
{
this.speaker.SetPlaybackDelaySettings(newMinDelaySoftValue, newMaxDelaySoftValue, newMaxDelayHardValue);
}
else
{
this.minDelaySoftInputField.text = this.speaker.PlaybackDelayMinSoft.ToString();
}
}
private void OnMaxDelaySoftChanged(string newMaxDelaySoftString)
{
int newMinDelaySoftValue = this.speaker.PlaybackDelayMinSoft;
int newMaxDelaySoftValue;
int newMaxDelayHardValue = this.speaker.PlaybackDelayMaxHard;
if (int.TryParse(newMaxDelaySoftString, out newMaxDelaySoftValue) && newMinDelaySoftValue < newMaxDelaySoftValue)
{
this.speaker.SetPlaybackDelaySettings(newMinDelaySoftValue, newMaxDelaySoftValue, newMaxDelayHardValue);
}
else
{
this.maxDelaySoftInputField.text = this.speaker.PlaybackDelayMaxSoft.ToString();
}
}
private void OnMaxDelayHardChanged(string newMaxDelayHardString)
{
int newMinDelaySoftValue = this.speaker.PlaybackDelayMinSoft;
int newMaxDelaySoftValue = this.speaker.PlaybackDelayMaxSoft;
int newMaxDelayHardValue;
if (int.TryParse(newMaxDelayHardString, out newMaxDelayHardValue) && newMaxDelayHardValue >= newMaxDelaySoftValue)
{
this.speaker.SetPlaybackDelaySettings(newMinDelaySoftValue, newMaxDelaySoftValue, newMaxDelayHardValue);
}
else
{
this.maxDelayHardInputField.text = this.speaker.PlaybackDelayMaxHard.ToString();
}
}
private void Update()
{
// TODO: It would be nice, if we could show if a user is actually talking right now (Voice Detection)
this.remoteIsTalking.enabled = this.speaker.IsPlaying;
this.bufferLagText.text = string.Concat("Buffer Lag: ", this.speaker.Lag);
}
private void OnDestroy()
{
if (this.loadBalancingClient != null)
{
this.loadBalancingClient.RemoveCallbackTarget(this);
}
}
private void SetNickname()
{
string nick = this.speaker.name;
if (this.speaker.Actor != null)
{
nick = this.speaker.Actor.NickName;
if (string.IsNullOrEmpty(nick))
{
nick = string.Concat("user ", this.speaker.Actor.ActorNumber);
}
}
this.nameText.text = nick;
}
private void SetMutedState()
{
this.SetMutedState(this.speaker.Actor.IsMuted());
}
protected virtual void SetMutedState(bool isMuted)
{
this.remoteIsMuting.enabled = isMuted;
}
protected virtual void OnActorPropertiesChanged(Player targetPlayer, Hashtable changedProps)
{
if (targetPlayer.ActorNumber == this.speaker.Actor.ActorNumber)
{
this.SetMutedState();
this.SetNickname();
}
}
public virtual void Init(VoiceConnection vC)
{
this.voiceConnection = vC;
this.loadBalancingClient = this.voiceConnection.Client;
this.loadBalancingClient.AddCallbackTarget(this);
}
#region IInRoomCallbacks
void IInRoomCallbacks.OnPlayerEnteredRoom(Player newPlayer)
{
}
void IInRoomCallbacks.OnPlayerLeftRoom(Player otherPlayer)
{
}
void IInRoomCallbacks.OnRoomPropertiesUpdate(Hashtable propertiesThatChanged)
{
}
void IInRoomCallbacks.OnPlayerPropertiesUpdate(Player targetPlayer, Hashtable changedProps)
{
this.OnActorPropertiesChanged(targetPlayer, changedProps);
}
void IInRoomCallbacks.OnMasterClientSwitched(Player newMasterClient)
{
}
#endregion
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 25daf05c976bc754b9a4ad8ae371c854
timeCreated: 1530628279
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,48 @@
namespace Photon.Voice.Unity.Demos
{
using UnityEngine.UI;
using UnityEngine;
public class SidebarToggle : MonoBehaviour
{
#pragma warning disable 649
[SerializeField]
private Button sidebarButton;
[SerializeField]
private RectTransform panelsHolder;
#pragma warning restore 649
private float sidebarWidth = 300f; // todo: get width dynamically at runtime
private bool sidebarOpen = true;
private void Awake()
{
this.sidebarButton.onClick.RemoveAllListeners();
this.sidebarButton.onClick.AddListener(this.ToggleSidebar);
this.ToggleSidebar(this.sidebarOpen);
}
[ContextMenu("ToggleSidebar")]
private void ToggleSidebar()
{
this.sidebarOpen = !this.sidebarOpen;
this.ToggleSidebar(this.sidebarOpen);
}
private void ToggleSidebar(bool open)
{
if (!open)
{
//this.panelsHolder.SetLeft(0);
this.panelsHolder.SetPosX(0);
}
else
{
//this.panelsHolder.SetLeft(this.sidebarWidth);
this.panelsHolder.SetPosX(this.sidebarWidth);
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0aeb3b11a4ed83e4cb11098a0cfb9c71
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,157 @@
namespace Photon.Voice.Unity.Demos
{
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using Object = UnityEngine.Object;
public static class UiExtensions
{
//http://answers.unity.com/answers/1610964/view.html
//https://gist.github.com/Josef212/b3f4bcf9cd827f5dc125ffc013548491
public static void SetPosX(this RectTransform rectTransform, float x)
{
rectTransform.anchoredPosition3D = new Vector3(x, rectTransform.anchoredPosition3D.y, rectTransform.anchoredPosition3D.z);
}
public static void SetHeight(this RectTransform rectTransform, float h)
{
rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, h);
}
//https://forum.unity.com/threads/change-the-value-of-a-toggle-without-triggering-onvaluechanged.275056/#post-2750271
#if !UNITY_2019_1_OR_NEWER
private static Toggle.ToggleEvent emptyToggleEvent = new Toggle.ToggleEvent();
#endif
// added to 2019.1 https://docs.unity3d.com/2019.1/Documentation/ScriptReference/UI.Toggle.SetIsOnWithoutNotify.html
public static void SetValue(this Toggle toggle, bool isOn)
{
#if UNITY_2019_1_OR_NEWER
toggle.SetIsOnWithoutNotify(isOn);
#else
Toggle.ToggleEvent originalEvent = toggle.onValueChanged;
toggle.onValueChanged = emptyToggleEvent;
toggle.isOn = isOn;
toggle.onValueChanged = originalEvent;
#endif
}
#if !UNITY_2019_1_OR_NEWER
private static Slider.SliderEvent emptySliderEvent = new Slider.SliderEvent();
#endif
public static void SetValue(this Slider slider, float v)
{
#if UNITY_2019_1_OR_NEWER
slider.SetValueWithoutNotify(v);
#else
Slider.SliderEvent originalEvent = slider.onValueChanged;
slider.onValueChanged = emptySliderEvent;
slider.value = v;
slider.onValueChanged = originalEvent;
#endif
}
#if !UNITY_2019_1_OR_NEWER
private static InputField.OnChangeEvent emptyInputFieldEvent = new InputField.OnChangeEvent();
private static InputField.SubmitEvent emptyInputFieldSubmitEvent = new InputField.SubmitEvent();
#endif
public static void SetValue(this InputField inputField, string v)
{
#if UNITY_2019_1_OR_NEWER
inputField.SetTextWithoutNotify(v);
#else
InputField.OnChangeEvent origianlEvent = inputField.onValueChanged;
InputField.SubmitEvent originalSubmitEvent = inputField.onEndEdit;
inputField.onValueChanged = emptyInputFieldEvent;
inputField.onEndEdit = emptyInputFieldSubmitEvent;
inputField.text = v;
inputField.onValueChanged = origianlEvent;
inputField.onEndEdit = originalSubmitEvent;
#endif
}
// https://forum.unity.com/threads/deleting-all-chidlren-of-an-object.92827/#post-2058407
/// <summary>
/// Calls GameObject.Destroy on all children of transform. and immediately detaches the children
/// from transform so after this call transform.childCount is zero.
/// </summary>
public static void DestroyChildren(this Transform transform)
{
if (!ReferenceEquals(null, transform) && transform)
{
for (int i = transform.childCount - 1; i >= 0; --i)
{
Transform child = transform.GetChild(i);
if (child && child.gameObject)
{
Object.Destroy(child.gameObject);
}
}
transform.DetachChildren();
}
}
public static void Hide(this CanvasGroup canvasGroup, bool blockRaycasts = false, bool interactable = false)
{
canvasGroup.alpha = 0f;
canvasGroup.blocksRaycasts = blockRaycasts;
canvasGroup.interactable = interactable;
}
public static void Show(this CanvasGroup canvasGroup, bool blockRaycasts = true, bool interactable = true)
{
canvasGroup.alpha = 1f;
canvasGroup.blocksRaycasts = blockRaycasts;
canvasGroup.interactable = interactable;
}
public static bool IsHidden(this CanvasGroup canvasGroup)
{
return canvasGroup.alpha <= 0f;
}
public static bool IsShown(this CanvasGroup canvasGroup)
{
return canvasGroup.alpha > 0f;
}
public static void SetSingleOnClickCallback(this Button button, UnityAction action)
{
button.onClick.RemoveAllListeners();
button.onClick.AddListener(action);
}
public static void SetSingleOnValueChangedCallback(this Toggle toggle, UnityAction<bool> action)
{
toggle.onValueChanged.RemoveAllListeners();
toggle.onValueChanged.AddListener(action);
}
public static void SetSingleOnValueChangedCallback(this InputField inputField, UnityAction<string> action)
{
inputField.onValueChanged.RemoveAllListeners();
inputField.onValueChanged.AddListener(action);
}
public static void SetSingleOnEndEditCallback(this InputField inputField, UnityAction<string> action)
{
inputField.onEndEdit.RemoveAllListeners();
inputField.onEndEdit.AddListener(action);
}
public static void SetSingleOnValueChangedCallback(this Dropdown inputField, UnityAction<int> action)
{
inputField.onValueChanged.RemoveAllListeners();
inputField.onValueChanged.AddListener(action);
}
public static void SetSingleOnValueChangedCallback(this Slider slider, UnityAction<float> action)
{
slider.onValueChanged.RemoveAllListeners();
slider.onValueChanged.AddListener(action);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 61bfa3948d4c1d34bb79ea542ab7217f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: