Reworked the dialogue system

Now the dialogue can use tags to add special effects
Reorganized project structure, updating may require adding some using statements
This commit is contained in:
Gerard Gascón 2022-09-15 17:27:28 +02:00 committed by GitHub
parent 95bad523b9
commit 0e8b8b1835
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
25 changed files with 1912 additions and 1266 deletions

View file

@ -12,7 +12,6 @@ This package will be updated once I find another useful tool or someone suggest
- Basic menu with **music and SFX sliders** as well as **resolution and quality dropdowns.** - Basic menu with **music and SFX sliders** as well as **resolution and quality dropdowns.**
- An **object pooler** with the ability to create pools with an undetermined size. - An **object pooler** with the ability to create pools with an undetermined size.
- A basic **scene manager** with a loading screen with progress bar. - A basic **scene manager** with a loading screen with progress bar.
- A **timer** that is displayed inside a TextMeshPro object.
All of that comes with some editor menu items for creating all of that as fast as possible. All of that comes with some editor menu items for creating all of that as fast as possible.
@ -37,6 +36,8 @@ Download latest package from the Release section Import SimpleTools.unitypackage
### AudioManager ### AudioManager
```csharp ```csharp
using SimpleTools.AudioManager;
AudioManager.instance.Play("Name"); //Plays the sound with that name AudioManager.instance.Play("Name"); //Plays the sound with that name
AudioManager.instance.Play("Name", 1f); //Starts playing the sound "Name" in 1 second AudioManager.instance.Play("Name", 1f); //Starts playing the sound "Name" in 1 second
AudioManager.instance.PlayOneShot("Name"); //Plays one shot of that sound (Useful for repeated sounds) AudioManager.instance.PlayOneShot("Name"); //Plays one shot of that sound (Useful for repeated sounds)
@ -63,6 +64,8 @@ AudioManager.instance.FadeMutedOut("Name", 1f); //Fade Out a sound without stopp
The SpawnFromPool function always return a GameObject The SpawnFromPool function always return a GameObject
```csharp ```csharp
using SimpleTools.ObjectPooler;
Pool pool; //The pool scriptable object goes here Pool pool; //The pool scriptable object goes here
Pooler.CreatePools(pool); //Create the pool, without creating it you cannot spawn it Pooler.CreatePools(pool); //Create the pool, without creating it you cannot spawn it
Pool[] pools; Pool[] pools;
@ -82,13 +85,28 @@ Pooler.SpawnFromPool("Name", Vector3.zero, Quaternion.identity, transform, true)
The Dialogue function returns a bool (true if it's talking, false if it has ended) The Dialogue function returns a bool (true if it's talking, false if it has ended)
```csharp ```csharp
using SimpleTools.DialogueSystem;
Dialogue dialogue; //The dialogue scriptable object goes here Dialogue dialogue; //The dialogue scriptable object goes here
DialogueSystem.instance.Dialogue(dialogue); //Start/Continue the dialogue DialogueSystem.instance.Dialogue(dialogue); //Start/Continue the dialogue
DialogueSystem.instance.Dialogue(dialogue, "Sound1", "Sound2"); //Start/Continue the dialogue with a random set of sounds for the text reveal
``` ```
Text commands:
| <color=color></color> | Sets font color within tags |
| --- | --- |
| <size=percentage></size> | Sets font size within tags |
| <sprite=index> | Draws a sprite from the TextMeshPro |
| <p:[tiny,short,normal,long,read]> | Pauses during a period of time |
| <anim:[wobble,wave,rainbow,shake]></anim> | Reproduces an animation |
| <sp:number></sp> | Changes reveal speed |
### SceneManager ### SceneManager
```csharp ```csharp
using SimpleTools.SceneManagement;
Loader.Load(0); //Loads a scene with a specific build index Loader.Load(0); //Loads a scene with a specific build index
Loader.Load("Scene"); //Loads a scene with a specific name Loader.Load("Scene"); //Loads a scene with a specific name
``` ```
@ -96,6 +114,8 @@ Loader.Load("Scene"); //Loads a scene with a specific name
### ScreenShake ### ScreenShake
```csharp ```csharp
using SimpleTools.Cinemachine;
ScreenShake.Shake(1f, .25f); //Shakes the camera with an intensity and duration ScreenShake.Shake(1f, .25f); //Shakes the camera with an intensity and duration
``` ```

View file

@ -2,261 +2,270 @@
using UnityEngine; using UnityEngine;
using System; using System;
public class AudioManager : MonoBehaviour{ namespace SimpleTools.AudioManager {
public class AudioManager : MonoBehaviour {
public static AudioManager instance; public static AudioManager instance;
[SerializeField] Sounds soundList = default; [SerializeField] Sounds soundList = default;
void Awake(){ void Awake() {
if(instance == null){ if (instance == null) {
instance = this; instance = this;
}else{ } else {
Destroy(gameObject); Destroy(gameObject);
return; return;
} }
DontDestroyOnLoad(gameObject); DontDestroyOnLoad(gameObject);
foreach(Sounds.List s in soundList.sounds){ foreach (Sounds.List s in soundList.sounds) {
if(string.IsNullOrEmpty(s.name) || string.IsNullOrWhiteSpace(s.name)){ if (string.IsNullOrEmpty(s.name) || string.IsNullOrWhiteSpace(s.name)) {
Debug.LogWarning("The name one sound is empty"); Debug.LogWarning("The name one sound is empty");
continue; continue;
} }
GameObject sound = new GameObject(s.name); GameObject sound = new GameObject(s.name);
sound.transform.parent = transform; sound.transform.parent = transform;
s.source = sound.AddComponent<AudioSource>(); s.source = sound.AddComponent<AudioSource>();
if(soundList.mainMixer && soundList.sfxMixer){ if (soundList.mainMixer && soundList.sfxMixer) {
if (s.type == Sounds.List.Type.Music) if (s.type == Sounds.List.Type.Music)
s.source.outputAudioMixerGroup = soundList.mainMixer; s.source.outputAudioMixerGroup = soundList.mainMixer;
else else
s.source.outputAudioMixerGroup = soundList.sfxMixer; s.source.outputAudioMixerGroup = soundList.sfxMixer;
} }
s.source.clip = s.clip; s.source.clip = s.clip;
s.source.volume = s.volume; s.source.volume = s.volume;
s.source.pitch = s.pitch; s.source.pitch = s.pitch;
s.source.loop = s.loop; s.source.loop = s.loop;
} }
} }
#region Play #region Play
/// <summary>Use this to play a sound with a specific name /// <summary>Use this to play a sound with a specific name
/// <para>It has to be in the Sound asset referenced in the AudioManager instance</para> /// <para>It has to be in the Sound asset referenced in the AudioManager instance</para>
/// </summary> /// </summary>
public void Play(string name){ public void Play(string name) {
Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name); Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name);
if(s == null){ if (s == null) {
Debug.LogWarning("Sound: " + name + " not found!"); Debug.LogWarning("Sound: " + name + " not found!");
return; return;
} }
s.source.pitch = s.RandomPitch; s.source.pitch = s.RandomPitch;
s.source.volume = s.RandomVolume; s.source.volume = s.RandomVolume;
s.source.Play(); s.source.Play();
} }
/// <summary>Use this to play a sound with a specific name and with a certain delay /// <summary>Use this to play a sound with a specific name and with a certain delay
/// <para>It has to be in the Sound asset referenced in the AudioManager instance</para> /// <para>It has to be in the Sound asset referenced in the AudioManager instance</para>
/// </summary> /// </summary>
public void Play(string name, float delay){ public void Play(string name, float delay) {
Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name); Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name);
if (s == null){ if (s == null) {
Debug.LogWarning("Sound: " + name + " not found!"); Debug.LogWarning("Sound: " + name + " not found!");
return; return;
} }
s.source.pitch = s.RandomPitch; s.source.pitch = s.RandomPitch;
s.source.volume = s.RandomVolume; s.source.volume = s.RandomVolume;
s.source.PlayDelayed(delay); s.source.PlayDelayed(delay);
} }
/// <summary>Use this to play one shot of a sound with a specific name /// <summary>Use this to play one shot of a sound with a specific name
/// <para>It has to be in the Sound asset referenced in the AudioManager instance</para> /// <para>It has to be in the Sound asset referenced in the AudioManager instance</para>
/// </summary> /// </summary>
public void PlayOneShot(string name){ public void PlayOneShot(string name) {
Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name); Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name);
if (s == null){ if (s == null) {
Debug.LogWarning("Sound: " + name + " not found!"); Debug.LogWarning("Sound: " + name + " not found!");
return; return;
} }
s.source.pitch = s.RandomPitch; s.source.pitch = s.RandomPitch;
s.source.volume = s.RandomVolume; s.source.volume = s.RandomVolume;
s.source.PlayOneShot(s.clip); s.source.PlayOneShot(s.clip);
} }
/// <summary>Use this to play an intro song and then start playing the song loop /// <summary>Use this to play an intro song and then start playing the song loop
/// <para>It has to be in the Sound asset referenced in the AudioManager instance</para> /// <para>It has to be in the Sound asset referenced in the AudioManager instance</para>
/// </summary> /// </summary>
public void PlayWithIntro(string intro, string song){ public void PlayWithIntro(string intro, string song) {
Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == intro); Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == intro);
if (s == null){ if (s == null) {
Debug.LogWarning("Sound: " + intro + " not found!"); Debug.LogWarning("Sound: " + intro + " not found!");
return; return;
} }
s.source.pitch = s.RandomPitch; s.source.pitch = s.RandomPitch;
s.source.volume = s.RandomVolume; s.source.volume = s.RandomVolume;
s.source.Play(); s.source.Play();
float introDuration = s.clip.length; float introDuration = s.clip.length;
Play(song, introDuration); Play(song, introDuration);
} }
#endregion /// <summary>Use this to play one shot of a random sound within a list
#region Pause /// <para>They have to be in the Sound asset referenced in the AudioManager instance</para>
/// <summary>Use this to pause a sound with a specific name /// </summary>
/// <para>It has to be in the Sound asset referenced in the AudioManager instance</para> public void PlayRandomSound(params string[] names) {
/// </summary> int random = UnityEngine.Random.Range(0, names.Length);
public void Pause(string name){ PlayOneShot(names[random]);
Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name); }
if (s == null){ #endregion
Debug.LogWarning("Sound: " + name + " not found!"); #region Pause
return; /// <summary>Use this to pause a sound with a specific name
} /// <para>It has to be in the Sound asset referenced in the AudioManager instance</para>
s.source.pitch = s.RandomPitch; /// </summary>
s.source.volume = s.RandomVolume; public void Pause(string name) {
s.source.Pause(); Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name);
} if (s == null) {
/// <summary>Use this to unpause a sound with a specific name Debug.LogWarning("Sound: " + name + " not found!");
/// <para>It has to be in the Sound asset referenced in the AudioManager instance</para> return;
/// </summary> }
public void UnPause(string name){ s.source.pitch = s.RandomPitch;
Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name); s.source.volume = s.RandomVolume;
if (s == null){ s.source.Pause();
Debug.LogWarning("Sound: " + name + " not found!"); }
return; /// <summary>Use this to unpause a sound with a specific name
} /// <para>It has to be in the Sound asset referenced in the AudioManager instance</para>
s.source.pitch = s.RandomPitch; /// </summary>
s.source.volume = s.RandomVolume; public void UnPause(string name) {
s.source.UnPause(); Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name);
} if (s == null) {
#endregion Debug.LogWarning("Sound: " + name + " not found!");
#region Stop return;
/// <summary>Use this to stop a sound with a specific name }
/// <para>It has to be in the Sound asset referenced in the AudioManager instance</para> s.source.pitch = s.RandomPitch;
/// </summary> s.source.volume = s.RandomVolume;
public void Stop(string name){ s.source.UnPause();
Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name); }
if (s == null){ #endregion
Debug.LogWarning("Sound: " + name + " not found!"); #region Stop
return; /// <summary>Use this to stop a sound with a specific name
} /// <para>It has to be in the Sound asset referenced in the AudioManager instance</para>
s.source.pitch = s.RandomPitch; /// </summary>
s.source.volume = s.RandomVolume; public void Stop(string name) {
s.source.Stop(); Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name);
} if (s == null) {
/// <summary>Use this to stop all the sounds Debug.LogWarning("Sound: " + name + " not found!");
/// <para>It has to be in the Sound asset referenced in the AudioManager instance</para> return;
/// </summary> }
public void StopAll(){ s.source.pitch = s.RandomPitch;
foreach (Sounds.List s in soundList.sounds){ s.source.volume = s.RandomVolume;
if (s.source){ s.source.Stop();
s.source.Stop(); }
} /// <summary>Use this to stop all the sounds
} /// <para>It has to be in the Sound asset referenced in the AudioManager instance</para>
} /// </summary>
#endregion public void StopAll() {
/// <summary>This function returns the AudioSource that contains a specific sound foreach (Sounds.List s in soundList.sounds) {
/// <para>It has to be in the Sound asset referenced in the AudioManager instance</para> if (s.source) {
/// </summary> s.source.Stop();
public AudioSource GetSource(string name){ }
Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name); }
if (s == null){ }
Debug.LogWarning("Sound: " + name + " not found!"); #endregion
return null; /// <summary>This function returns the AudioSource that contains a specific sound
} /// <para>It has to be in the Sound asset referenced in the AudioManager instance</para>
return s.source; /// </summary>
} public AudioSource GetSource(string name) {
#region Fades Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name);
/// <summary>Use this to start playing a sound with a fade in if (s == null) {
/// <para>It has to be in the Sound asset referenced in the AudioManager instance</para> Debug.LogWarning("Sound: " + name + " not found!");
/// </summary> return null;
public void FadeIn(string name, float duration){ }
StartCoroutine(FadeInCoroutine(name, duration)); return s.source;
} }
IEnumerator FadeInCoroutine(string name, float fadeTime){ #region Fades
AudioSource audioSource = GetSource(name); /// <summary>Use this to start playing a sound with a fade in
if (audioSource != null && !audioSource.isPlaying){ /// <para>It has to be in the Sound asset referenced in the AudioManager instance</para>
float volume = audioSource.volume; /// </summary>
audioSource.volume = 0; public void FadeIn(string name, float duration) {
audioSource.Play(); StartCoroutine(FadeInCoroutine(name, duration));
while (audioSource.volume < volume){ }
audioSource.volume += Time.deltaTime / fadeTime; IEnumerator FadeInCoroutine(string name, float fadeTime) {
yield return null; AudioSource audioSource = GetSource(name);
} if (audioSource != null && !audioSource.isPlaying) {
float volume = audioSource.volume;
audioSource.volume = 0;
audioSource.Play();
while (audioSource.volume < volume) {
audioSource.volume += Time.deltaTime / fadeTime;
yield return null;
}
audioSource.volume = volume; audioSource.volume = volume;
} }
} }
/// <summary>Use this to stop playing a sound with a fade out /// <summary>Use this to stop playing a sound with a fade out
/// <para>It has to be in the Sound asset referenced in the AudioManager instance</para> /// <para>It has to be in the Sound asset referenced in the AudioManager instance</para>
/// </summary> /// </summary>
public void FadeOut(string name, float duration){ public void FadeOut(string name, float duration) {
StartCoroutine(FadeOutCoroutine(name, duration)); StartCoroutine(FadeOutCoroutine(name, duration));
} }
IEnumerator FadeOutCoroutine(string name, float fadeTime){ IEnumerator FadeOutCoroutine(string name, float fadeTime) {
AudioSource audioSource = GetSource(name); AudioSource audioSource = GetSource(name);
if (audioSource && audioSource.isPlaying){ if (audioSource && audioSource.isPlaying) {
float startVolume = audioSource.volume; float startVolume = audioSource.volume;
while (audioSource.volume > 0){ while (audioSource.volume > 0) {
audioSource.volume -= startVolume * Time.deltaTime / fadeTime; audioSource.volume -= startVolume * Time.deltaTime / fadeTime;
yield return null; yield return null;
} }
audioSource.Stop(); audioSource.Stop();
audioSource.volume = startVolume; audioSource.volume = startVolume;
} }
} }
/// <summary>Use this to start playing a sound muted /// <summary>Use this to start playing a sound muted
/// <para>It has to be in the Sound asset referenced in the AudioManager instance</para> /// <para>It has to be in the Sound asset referenced in the AudioManager instance</para>
/// </summary> /// </summary>
public void PlayMuted(string name){ public void PlayMuted(string name) {
Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name); Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name);
if (s == null){ if (s == null) {
Debug.LogWarning("Sound: " + name + " not found!"); Debug.LogWarning("Sound: " + name + " not found!");
return; return;
} }
s.source.pitch = s.RandomPitch; s.source.pitch = s.RandomPitch;
s.source.volume = 0f; s.source.volume = 0f;
s.source.Play(); s.source.Play();
} }
/// <summary>Use this to fade in a sound that is currently muted /// <summary>Use this to fade in a sound that is currently muted
/// <para>It has to be in the Sound asset referenced in the AudioManager instance</para> /// <para>It has to be in the Sound asset referenced in the AudioManager instance</para>
/// <para>WARNING: If the PlayMuted hasn't been called before, this function won't work</para> /// <para>WARNING: If the PlayMuted hasn't been called before, this function won't work</para>
/// </summary> /// </summary>
public void FadeMutedIn(string name, float duration){ public void FadeMutedIn(string name, float duration) {
StartCoroutine(FadeMutedInCoroutine(name, duration)); StartCoroutine(FadeMutedInCoroutine(name, duration));
} }
IEnumerator FadeMutedInCoroutine(string name, float fadeTime){ IEnumerator FadeMutedInCoroutine(string name, float fadeTime) {
Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name); Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name);
if (s == null){ if (s == null) {
Debug.LogWarning("Sound: " + name + " not found!"); Debug.LogWarning("Sound: " + name + " not found!");
yield break; yield break;
} }
while (s.source.volume < s.volume){ while (s.source.volume < s.volume) {
s.source.volume += Time.deltaTime / fadeTime; s.source.volume += Time.deltaTime / fadeTime;
yield return null; yield return null;
} }
s.source.volume = s.volume; s.source.volume = s.volume;
} }
/// <summary>Use this to fade out a sound and keep playing that muted /// <summary>Use this to fade out a sound and keep playing that muted
/// <para>It has to be in the Sound asset referenced in the AudioManager instance</para> /// <para>It has to be in the Sound asset referenced in the AudioManager instance</para>
/// </summary> /// </summary>
public void FadeMutedOut(string name, float duration){ public void FadeMutedOut(string name, float duration) {
StartCoroutine(FadeMutedOutCoroutine(name, duration)); StartCoroutine(FadeMutedOutCoroutine(name, duration));
} }
IEnumerator FadeMutedOutCoroutine(string name, float fadeTime){ IEnumerator FadeMutedOutCoroutine(string name, float fadeTime) {
Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name); Sounds.List s = Array.Find(soundList.sounds, sound => sound.name == name);
if (s == null){ if (s == null) {
Debug.LogWarning("Sound: " + name + " not found!"); Debug.LogWarning("Sound: " + name + " not found!");
yield break; yield break;
} }
while (s.source.volume > 0){ while (s.source.volume > 0) {
s.source.volume -= Time.deltaTime / fadeTime; s.source.volume -= Time.deltaTime / fadeTime;
yield return null; yield return null;
} }
s.source.volume = 0; s.source.volume = 0;
} }
#endregion #endregion
}
} }

View file

@ -1,50 +1,53 @@
using UnityEngine; using UnityEngine;
using UnityEngine.Audio; using UnityEngine.Audio;
[CreateAssetMenu(fileName = "Sounds", menuName = "Simple Tools/Sounds", order = 11)] namespace SimpleTools.AudioManager {
public class Sounds : ScriptableObject{ [CreateAssetMenu(fileName = "Sounds", menuName = "Simple Tools/Sounds", order = 11)]
public class Sounds : ScriptableObject {
[Tooltip("The music mixer.")] [Tooltip("The music mixer.")]
public AudioMixerGroup mainMixer = default; public AudioMixerGroup mainMixer = default;
[Tooltip("The SFX mixer.")] [Tooltip("The SFX mixer.")]
public AudioMixerGroup sfxMixer = default; public AudioMixerGroup sfxMixer = default;
public List[] sounds; public List[] sounds;
[System.Serializable] public class List{ [System.Serializable]
[Tooltip("Name of the sound. Each name has to be different between each other.")] public class List {
public string name; [Tooltip("Name of the sound. Each name has to be different between each other.")]
public string name;
public AudioClip clip; public AudioClip clip;
[System.Serializable] public enum Type { Music, SFX } [System.Serializable] public enum Type { Music, SFX }
[Space] [Space]
[Tooltip("Is it part of the music or the SFX?")] public Type type; [Tooltip("Is it part of the music or the SFX?")] public Type type;
[Space] [Space]
[Tooltip("Default volume of the sound."), Range(0f, 1f)] public float volume; [Tooltip("Default volume of the sound."), Range(0f, 1f)] public float volume;
[Tooltip("Variance percentage of the volume"), Range(0f, 1f)] public float volumeVariance; [Tooltip("Variance percentage of the volume"), Range(0f, 1f)] public float volumeVariance;
[Tooltip("Default pitch of the sound."), Range(.1f, 3f)] public float pitch; [Tooltip("Default pitch of the sound."), Range(.1f, 3f)] public float pitch;
[Tooltip("Variance percentage of the pitch"), Range(0f, 1f)] public float pitchVariance; [Tooltip("Variance percentage of the pitch"), Range(0f, 1f)] public float pitchVariance;
public bool loop; public bool loop;
[HideInInspector] public AudioSource source; [HideInInspector] public AudioSource source;
float randomVolume; float randomVolume;
public float RandomVolume{ public float RandomVolume {
get{ get {
randomVolume = volume * (1f + Random.Range(-volumeVariance / 2f, volumeVariance / 2f)); randomVolume = volume * (1f + Random.Range(-volumeVariance / 2f, volumeVariance / 2f));
return randomVolume; return randomVolume;
} }
} }
float randomPitch; float randomPitch;
public float RandomPitch{ public float RandomPitch {
get{ get {
randomPitch = pitch * (1f + Random.Range(-pitchVariance / 2f, pitchVariance / 2f)); randomPitch = pitch * (1f + Random.Range(-pitchVariance / 2f, pitchVariance / 2f));
return randomPitch; return randomPitch;
} }
} }
} }
}
} }

View file

@ -1,38 +1,40 @@
using UnityEngine; using UnityEngine;
using Cinemachine; using Cinemachine;
public class CMCameraTrigger : MonoBehaviour{ namespace SimpleTools.Cinemachine {
public class CMCameraTrigger : MonoBehaviour {
CinemachineVirtualCamera vcam; CinemachineVirtualCamera vcam;
void Awake(){ void Awake() {
vcam = GetComponentInChildren<CinemachineVirtualCamera>(true); vcam = GetComponentInChildren<CinemachineVirtualCamera>(true);
vcam.gameObject.SetActive(false); vcam.gameObject.SetActive(false);
} }
#region 3D #region 3D
void OnTriggerEnter(Collider col){ void OnTriggerEnter(Collider col) {
if (col.CompareTag("Player")){ if (col.CompareTag("Player")) {
vcam.gameObject.SetActive(true); vcam.gameObject.SetActive(true);
} }
} }
void OnTriggerExit(Collider col){ void OnTriggerExit(Collider col) {
if (col.CompareTag("Player")){ if (col.CompareTag("Player")) {
vcam.gameObject.SetActive(true); vcam.gameObject.SetActive(true);
} }
} }
#endregion #endregion
#region 2D #region 2D
void OnTriggerEnter2D(Collider2D col){ void OnTriggerEnter2D(Collider2D col) {
if (col.CompareTag("Player")){ if (col.CompareTag("Player")) {
vcam.gameObject.SetActive(true); vcam.gameObject.SetActive(true);
} }
} }
void OnTriggerExit2D(Collider2D col){ void OnTriggerExit2D(Collider2D col) {
if (col.CompareTag("Player")){ if (col.CompareTag("Player")) {
vcam.gameObject.SetActive(false); vcam.gameObject.SetActive(false);
} }
} }
#endregion #endregion
}
} }

View file

@ -1,36 +1,38 @@
using Cinemachine; using Cinemachine;
using UnityEngine; using UnityEngine;
public static class ScreenShake{ namespace SimpleTools.Cinemachine {
public static class ScreenShake {
static CinemachineVirtualCamera vCam; static CinemachineVirtualCamera vCam;
static ScreenShakeUpdate shakeUpdate; static ScreenShakeUpdate shakeUpdate;
class ScreenShakeUpdate : MonoBehaviour { class ScreenShakeUpdate : MonoBehaviour {
[HideInInspector] public float shakeTimer; [HideInInspector] public float shakeTimer;
[HideInInspector] public float shakeTimerTotal; [HideInInspector] public float shakeTimerTotal;
[HideInInspector] public float startingIntensity; [HideInInspector] public float startingIntensity;
void Update(){ void Update() {
if (shakeTimer > 0){ if (shakeTimer > 0) {
shakeTimer -= Time.deltaTime; shakeTimer -= Time.deltaTime;
CinemachineBasicMultiChannelPerlin multiChannelPerlin = vCam.GetCinemachineComponent<CinemachineBasicMultiChannelPerlin>(); CinemachineBasicMultiChannelPerlin multiChannelPerlin = vCam.GetCinemachineComponent<CinemachineBasicMultiChannelPerlin>();
multiChannelPerlin.m_AmplitudeGain = Mathf.Lerp(startingIntensity, 0f, 1 - (shakeTimer / shakeTimerTotal)); multiChannelPerlin.m_AmplitudeGain = Mathf.Lerp(startingIntensity, 0f, 1 - (shakeTimer / shakeTimerTotal));
} }
} }
} }
/// <summary>Shake the camera /// <summary>Shake the camera
/// <para>It needs a cinemachine camera with a noise profile in it.</para> /// <para>It needs a cinemachine camera with a noise profile in it.</para>
/// </summary> /// </summary>
public static void Shake(float intensity, float time){ public static void Shake(float intensity, float time) {
if(vCam == null){ if (vCam == null) {
vCam = Camera.main.GetComponent<CinemachineBrain>().ActiveVirtualCamera.VirtualCameraGameObject.GetComponent<CinemachineVirtualCamera>(); vCam = Camera.main.GetComponent<CinemachineBrain>().ActiveVirtualCamera.VirtualCameraGameObject.GetComponent<CinemachineVirtualCamera>();
} }
if(shakeUpdate == null){ if (shakeUpdate == null) {
shakeUpdate = new GameObject("ShakeUpdate").AddComponent<ScreenShakeUpdate>(); shakeUpdate = new GameObject("ShakeUpdate").AddComponent<ScreenShakeUpdate>();
} }
shakeUpdate.startingIntensity = intensity; shakeUpdate.startingIntensity = intensity;
shakeUpdate.shakeTimer = shakeUpdate.shakeTimerTotal = time; shakeUpdate.shakeTimer = shakeUpdate.shakeTimerTotal = time;
} }
}
} }

View file

@ -1,12 +1,16 @@
using UnityEngine; using UnityEngine;
[CreateAssetMenu(fileName = "New Character", menuName = "Simple Tools/Character", order = 11)] namespace SimpleTools.DialogueSystem {
public class Dialogue : ScriptableObject{ [CreateAssetMenu(fileName = "New Dialogue", menuName = "Simple Tools/Dialogue", order = 11)]
public class Dialogue : ScriptableObject {
public DialogueBox[] sentences;
}
public bool displayName; [System.Serializable]
public string characterName; public class DialogueBox {
public bool displayName;
[Space] public string characterName;
public Sprite characterImage; public Sprite characterImage;
[TextArea] public string[] sentences; [TextArea(5, 10)] public string sentence;
}
} }

View file

@ -0,0 +1,112 @@
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace SimpleTools.DialogueSystem {
public class DialogueManager : MonoBehaviour {
DialogueVertexAnimator dialogueVertexAnimator;
Queue<string> sentences;
Queue<bool> displayNames;
Queue<string> characterNames;
Queue<Sprite> characterImages;
bool talking;
public DialogueItems dialogueItems;
public static DialogueManager instance;
void Awake() {
instance = this;
sentences = new Queue<string>();
displayNames = new Queue<bool>();
characterNames = new Queue<string>();
characterImages = new Queue<Sprite>();
dialogueVertexAnimator = new DialogueVertexAnimator(dialogueItems.textBox);
}
public bool Dialogue(Dialogue dialogue) {
return Dialogue(dialogue, "");
}
public bool Dialogue(Dialogue dialogue, params string[] sounds) {
if (sounds != null)
dialogueVertexAnimator.SetAudioSourceGroup(sounds);
if (!talking) {
sentences.Clear();
if (dialogue.sentences.Length != 0) {
foreach (DialogueBox sentence in dialogue.sentences) {
sentences.Enqueue(sentence.sentence);
displayNames.Enqueue(sentence.displayName);
characterNames.Enqueue(sentence.characterName);
characterImages.Enqueue(sentence.characterImage);
}
} else {
sentences.Enqueue("I am error. No text has been added");
}
talking = true;
if (sentences.Count == 0) {
talking = false;
return false;
}
string sentenceToShow = sentences.Peek();
bool displayName = displayNames.Peek();
string characterName = characterNames.Peek();
Sprite characterImage = characterImages.Peek();
if (PlayDialogue(sentenceToShow, displayName, characterName, characterImage)) {
sentences.Dequeue();
displayNames.Dequeue();
characterNames.Dequeue();
characterImages.Dequeue();
}
return true;
} else {
if (sentences.Count == 0) {
talking = false;
return false;
}
string sentenceToShow = sentences.Peek();
bool displayName = displayNames.Peek();
string characterName = characterNames.Peek();
Sprite characterImage = characterImages.Peek();
if (PlayDialogue(sentenceToShow, displayName, characterName, characterImage)) {
sentences.Dequeue();
displayNames.Dequeue();
characterNames.Dequeue();
characterImages.Dequeue();
}
return true;
}
}
private Coroutine typeRoutine = null;
bool PlayDialogue(string message, bool displayName = false, string characterName = "", Sprite characterImage = null) {
if (dialogueVertexAnimator.IsMessageAnimating()) {
dialogueVertexAnimator.SkipToEndOfCurrentMessage();
return false; //Next message hasn't been shown because the current one is still animating.
}
this.EnsureCoroutineStopped(ref typeRoutine);
dialogueVertexAnimator.textAnimating = false;
List<DialogueCommand> commands = DialogueUtility.ProcessInputString(message, out string totalTextMessage);
typeRoutine = StartCoroutine(dialogueVertexAnimator.AnimateTextIn(commands, totalTextMessage, null));
dialogueItems.characterImage.sprite = characterImage;
dialogueItems.characterName.text = displayName ? characterName : "???";
return true; //Next message shown successfully
}
}
[System.Serializable]
public struct DialogueItems {
public Image characterImage;
public TMP_Text characterName;
public TMP_Text textBox;
public Canvas canvas;
}
}

View file

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

View file

@ -0,0 +1,152 @@
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System;
namespace SimpleTools.DialogueSystem {
public class DialogueUtility : MonoBehaviour {
// grab the remainder of the text until ">" or end of string
const string REMAINDER_REGEX = "(.*?((?=>)|(/|$)))";
const string PAUSE_REGEX_STRING = "<p:(?<pause>" + REMAINDER_REGEX + ")>";
static readonly Regex pauseRegex = new Regex(PAUSE_REGEX_STRING);
const string SPEED_REGEX_STRING = "<sp:(?<speed>" + REMAINDER_REGEX + ")>";
static readonly Regex speedRegex = new Regex(SPEED_REGEX_STRING);
const string ANIM_START_REGEX_STRING = "<anim:(?<anim>" + REMAINDER_REGEX + ")>";
static readonly Regex animStartRegex = new Regex(ANIM_START_REGEX_STRING);
const string ANIM_END_REGEX_STRING = "</anim>";
static readonly Regex animEndRegex = new Regex(ANIM_END_REGEX_STRING);
static readonly Dictionary<string, float> pauseDictionary = new Dictionary<string, float>{
{ "tiny", .1f },
{ "short", .25f },
{ "normal", 0.666f },
{ "long", 1f },
{ "read", 2f },
};
public static List<DialogueCommand> ProcessInputString(string message, out string processedMessage) {
List<DialogueCommand> result = new List<DialogueCommand>();
processedMessage = message;
processedMessage = HandlePauseTags(processedMessage, result);
processedMessage = HandleSpeedTags(processedMessage, result);
processedMessage = HandleAnimStartTags(processedMessage, result);
processedMessage = HandleAnimEndTags(processedMessage, result);
return result;
}
static string HandleAnimEndTags(string processedMessage, List<DialogueCommand> result) {
MatchCollection animEndMatches = animEndRegex.Matches(processedMessage);
foreach (Match match in animEndMatches) {
result.Add(new DialogueCommand {
position = VisibleCharactersUpToIndex(processedMessage, match.Index),
type = DialogueCommandType.AnimEnd,
});
}
processedMessage = Regex.Replace(processedMessage, ANIM_END_REGEX_STRING, "");
return processedMessage;
}
static string HandleAnimStartTags(string processedMessage, List<DialogueCommand> result) {
MatchCollection animStartMatches = animStartRegex.Matches(processedMessage);
foreach (Match match in animStartMatches) {
string stringVal = match.Groups["anim"].Value;
result.Add(new DialogueCommand {
position = VisibleCharactersUpToIndex(processedMessage, match.Index),
type = DialogueCommandType.AnimStart,
textAnimValue = GetTextAnimationType(stringVal)
});
}
processedMessage = Regex.Replace(processedMessage, ANIM_START_REGEX_STRING, "");
return processedMessage;
}
static string HandleSpeedTags(string processedMessage, List<DialogueCommand> result) {
MatchCollection speedMatches = speedRegex.Matches(processedMessage);
foreach (Match match in speedMatches) {
string stringVal = match.Groups["speed"].Value;
if (!float.TryParse(stringVal, out float val)) {
val = 150f;
}
result.Add(new DialogueCommand {
position = VisibleCharactersUpToIndex(processedMessage, match.Index),
type = DialogueCommandType.TextSpeedChange,
floatValue = val
});
}
processedMessage = Regex.Replace(processedMessage, SPEED_REGEX_STRING, "");
return processedMessage;
}
static string HandlePauseTags(string processedMessage, List<DialogueCommand> result) {
MatchCollection pauseMatches = pauseRegex.Matches(processedMessage);
foreach (Match match in pauseMatches) {
string val = match.Groups["pause"].Value;
string pauseName = val;
Debug.Assert(pauseDictionary.ContainsKey(pauseName), "no pause registered for '" + pauseName + "'");
result.Add(new DialogueCommand {
position = VisibleCharactersUpToIndex(processedMessage, match.Index),
type = DialogueCommandType.Pause,
floatValue = pauseDictionary[pauseName]
});
}
processedMessage = Regex.Replace(processedMessage, PAUSE_REGEX_STRING, "");
return processedMessage;
}
static TextAnimationType GetTextAnimationType(string stringVal) {
TextAnimationType result;
try {
result = (TextAnimationType)Enum.Parse(typeof(TextAnimationType), stringVal, true);
} catch (ArgumentException) {
Debug.LogError("Invalid Text Animation Type: " + stringVal);
result = TextAnimationType.none;
}
return result;
}
static int VisibleCharactersUpToIndex(string message, int index) {
int result = 0;
bool insideBrackets = false;
for (int i = 0; i < index; i++) {
if (message[i] == '<') {
insideBrackets = true;
} else if (message[i] == '>') {
insideBrackets = false;
result--;
}
if (!insideBrackets) {
result++;
} else if (i + 6 < index && message.Substring(i, 6) == "sprite") {
result++;
}
}
return result;
}
}
public struct DialogueCommand {
public int position;
public DialogueCommandType type;
public float floatValue;
public string stringValue;
public TextAnimationType textAnimValue;
}
public enum DialogueCommandType {
Pause,
TextSpeedChange,
AnimStart,
AnimEnd
}
public enum TextAnimationType {
none,
shake,
wave,
wobble,
rainbow,
}
}

View file

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

View file

@ -0,0 +1,262 @@
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
namespace SimpleTools.DialogueSystem {
public class DialogueVertexAnimator {
public bool textAnimating = false;
bool stopAnimating = false;
readonly TMP_Text textBox;
string[] audioSourceGroup;
public void SetAudioSourceGroup(params string[] _audioSourceGroup) {
audioSourceGroup = _audioSourceGroup;
}
public DialogueVertexAnimator(TMP_Text _textBox) {
textBox = _textBox;
}
static readonly Color32 clear = new Color32(0, 0, 0, 0);
const float CHAR_ANIM_TIME = 0.07f;
static readonly Vector3 vecZero = Vector3.zero;
public IEnumerator AnimateTextIn(List<DialogueCommand> commands, string processedMessage, Action onFinish) {
textAnimating = true;
float secondsPerCharacter = 1f / 150f;
float timeOfLastCharacter = 0;
TextAnimInfo[] textAnimInfo = SeparateOutTextAnimInfo(commands);
TMP_TextInfo textInfo = textBox.textInfo;
for (int i = 0; i < textInfo.meshInfo.Length; i++) {
TMP_MeshInfo meshInfer = textInfo.meshInfo[i];
if (meshInfer.vertices != null) {
for (int j = 0; j < meshInfer.vertices.Length; j++) {
meshInfer.vertices[j] = vecZero;
}
}
}
textBox.text = processedMessage;
textBox.ForceMeshUpdate();
TMP_MeshInfo[] cachedMeshInfo = textInfo.CopyMeshInfoVertexData();
Color32[][] originalColors = new Color32[textInfo.meshInfo.Length][];
for (int i = 0; i < originalColors.Length; i++) {
Color32[] theColors = textInfo.meshInfo[i].colors32;
originalColors[i] = new Color32[theColors.Length];
Array.Copy(theColors, originalColors[i], theColors.Length);
}
int charCount = textInfo.characterCount;
float[] charAnimStartTimes = new float[charCount];
for (int i = 0; i < charCount; i++) {
charAnimStartTimes[i] = -1;
}
int visableCharacterIndex = 0;
while (true) {
if (stopAnimating) {
for (int i = visableCharacterIndex; i < charCount; i++) {
charAnimStartTimes[i] = Time.unscaledTime;
}
visableCharacterIndex = charCount;
FinishAnimating(onFinish);
}
if (ShouldShowNextCharacter(secondsPerCharacter, timeOfLastCharacter)) {
if (visableCharacterIndex <= charCount) {
ExecuteCommandsForCurrentIndex(commands, visableCharacterIndex, ref secondsPerCharacter, ref timeOfLastCharacter);
if (visableCharacterIndex < charCount && ShouldShowNextCharacter(secondsPerCharacter, timeOfLastCharacter)) {
charAnimStartTimes[visableCharacterIndex] = Time.unscaledTime;
PlayDialogueSound();
visableCharacterIndex++;
timeOfLastCharacter = Time.unscaledTime;
if (visableCharacterIndex == charCount) {
FinishAnimating(onFinish);
}
}
}
}
for (int j = 0; j < charCount; j++) {
TMP_CharacterInfo charInfo = textInfo.characterInfo[j];
if (charInfo.isVisible) {
int vertexIndex = charInfo.vertexIndex;
int materialIndex = charInfo.materialReferenceIndex;
Color32[] destinationColors = textInfo.meshInfo[materialIndex].colors32;
Color32 theColor = j < visableCharacterIndex ? originalColors[materialIndex][vertexIndex] : clear;
destinationColors[vertexIndex + 0] = theColor;
destinationColors[vertexIndex + 1] = theColor;
destinationColors[vertexIndex + 2] = theColor;
destinationColors[vertexIndex + 3] = theColor;
Vector3[] sourceVertices = cachedMeshInfo[materialIndex].vertices;
Vector3[] destinationVertices = textInfo.meshInfo[materialIndex].vertices;
float charSize = 0;
float charAnimStartTime = charAnimStartTimes[j];
if (charAnimStartTime >= 0) {
float timeSinceAnimStart = Time.unscaledTime - charAnimStartTime;
charSize = Mathf.Min(1, timeSinceAnimStart / CHAR_ANIM_TIME);
}
Vector3 animPosAdjustment = GetAnimPosAdjustment(textAnimInfo, j, textBox.fontSize, Time.unscaledTime);
Vector3 offset = (sourceVertices[vertexIndex + 0] + sourceVertices[vertexIndex + 2]) / 2;
destinationVertices[vertexIndex + 0] = ((sourceVertices[vertexIndex + 0] - offset) * charSize) + offset + animPosAdjustment;
destinationVertices[vertexIndex + 1] = ((sourceVertices[vertexIndex + 1] - offset) * charSize) + offset + animPosAdjustment;
destinationVertices[vertexIndex + 2] = ((sourceVertices[vertexIndex + 2] - offset) * charSize) + offset + animPosAdjustment;
destinationVertices[vertexIndex + 3] = ((sourceVertices[vertexIndex + 3] - offset) * charSize) + offset + animPosAdjustment;
for (int i = 0; i < 4; i++) {
Vector3 animVertexAdjustment = GetAnimVertexAdjustment(textAnimInfo, j, textBox.fontSize, Time.unscaledTime + i);
destinationVertices[vertexIndex + i] += animVertexAdjustment;
Color animColorAdjustment = GetAnimColorAdjustment(textAnimInfo, j, Time.unscaledTime + i, destinationVertices[vertexIndex + i]);
if (animColorAdjustment == Color.white)
continue;
destinationColors[vertexIndex + i] += animColorAdjustment;
}
}
}
textBox.UpdateVertexData(TMP_VertexDataUpdateFlags.Colors32);
for (int i = 0; i < textInfo.meshInfo.Length; i++) {
TMP_MeshInfo theInfo = textInfo.meshInfo[i];
theInfo.mesh.vertices = theInfo.vertices;
textBox.UpdateGeometry(theInfo.mesh, i);
}
yield return null;
}
}
void ExecuteCommandsForCurrentIndex(List<DialogueCommand> commands, int visableCharacterIndex, ref float secondsPerCharacter, ref float timeOfLastCharacter) {
for (int i = 0; i < commands.Count; i++) {
DialogueCommand command = commands[i];
if (command.position == visableCharacterIndex) {
switch (command.type) {
case DialogueCommandType.Pause:
timeOfLastCharacter = Time.unscaledTime + command.floatValue;
break;
case DialogueCommandType.TextSpeedChange:
secondsPerCharacter = 1f / command.floatValue;
break;
}
commands.RemoveAt(i);
i--;
}
}
}
void FinishAnimating(Action onFinish) {
textAnimating = false;
stopAnimating = false;
onFinish?.Invoke();
}
const float NOISE_MAGNITUDE_ADJUSTMENT = 0.06f;
const float NOISE_FREQUENCY_ADJUSTMENT = 15f;
const float WAVE_MAGNITUDE_ADJUSTMENT = 0.06f;
const float WOBBLE_MAGNITUDE_ADJUSTMENT = 0.5f;
const float RAINBOW_LENGTH_ADJUSTMENT = .001f;
Vector3 GetAnimPosAdjustment(TextAnimInfo[] textAnimInfo, int charIndex, float fontSize, float time) {
float x = 0;
float y = 0;
for (int i = 0; i < textAnimInfo.Length; i++) {
TextAnimInfo info = textAnimInfo[i];
if (charIndex >= info.startIndex && charIndex < info.endIndex) {
if (info.type == TextAnimationType.shake) {
float scaleAdjust = fontSize * NOISE_MAGNITUDE_ADJUSTMENT;
x += (Mathf.PerlinNoise((charIndex + time) * NOISE_FREQUENCY_ADJUSTMENT, 0) - 0.5f) * scaleAdjust;
y += (Mathf.PerlinNoise((charIndex + time) * NOISE_FREQUENCY_ADJUSTMENT, 1000) - 0.5f) * scaleAdjust;
} else if (info.type == TextAnimationType.wave) {
y += Mathf.Sin((charIndex * 1.5f) + (time * 6)) * fontSize * WAVE_MAGNITUDE_ADJUSTMENT;
}
}
}
return new Vector3(x, y, 0);
}
Vector3 GetAnimVertexAdjustment(TextAnimInfo[] textAnimInfo, int charIndex, float fontSize, float time) {
float x = 0;
float y = 0;
for (int i = 0; i < textAnimInfo.Length; i++) {
TextAnimInfo info = textAnimInfo[i];
if (charIndex >= info.startIndex && charIndex < info.endIndex) {
if (info.type == TextAnimationType.wobble) {
float scaleAdjust = fontSize * NOISE_MAGNITUDE_ADJUSTMENT;
x = Mathf.Sin(time * 3.3f) * scaleAdjust * WOBBLE_MAGNITUDE_ADJUSTMENT;
y = Mathf.Cos(time * 2.5f) * scaleAdjust * WOBBLE_MAGNITUDE_ADJUSTMENT;
}
}
}
return new Vector3(x, y, 0);
}
Color GetAnimColorAdjustment(TextAnimInfo[] textAnimInfo, int charIndex, float time, Vector3 destinationVertice) {
Color color = Color.white;
for (int i = 0; i < textAnimInfo.Length; i++) {
TextAnimInfo info = textAnimInfo[i];
if (charIndex >= info.startIndex && charIndex < info.endIndex) {
if (info.type == TextAnimationType.rainbow) {
color = Color.HSVToRGB(Mathf.Repeat((time + destinationVertice.x * RAINBOW_LENGTH_ADJUSTMENT), 1f), .6f, 1);
}
}
}
return color;
}
static bool ShouldShowNextCharacter(float secondsPerCharacter, float timeOfLastCharacter) {
return (Time.unscaledTime - timeOfLastCharacter) > secondsPerCharacter;
}
public void SkipToEndOfCurrentMessage() {
if (textAnimating) {
stopAnimating = true;
}
}
public bool IsMessageAnimating() {
return textAnimating;
}
float timeUntilNextDialogueSound = 0;
float lastDialogueSound = 0;
void PlayDialogueSound() {
if (Time.unscaledTime - lastDialogueSound > timeUntilNextDialogueSound) {
timeUntilNextDialogueSound = UnityEngine.Random.Range(0.02f, 0.08f);
lastDialogueSound = Time.unscaledTime;
if (audioSourceGroup != null)
AudioManager.AudioManager.instance.PlayRandomSound(audioSourceGroup);
}
}
TextAnimInfo[] SeparateOutTextAnimInfo(List<DialogueCommand> commands) {
List<TextAnimInfo> tempResult = new List<TextAnimInfo>();
List<DialogueCommand> animStartCommands = new List<DialogueCommand>();
List<DialogueCommand> animEndCommands = new List<DialogueCommand>();
for (int i = 0; i < commands.Count; i++) {
DialogueCommand command = commands[i];
if (command.type == DialogueCommandType.AnimStart) {
animStartCommands.Add(command);
commands.RemoveAt(i);
i--;
} else if (command.type == DialogueCommandType.AnimEnd) {
animEndCommands.Add(command);
commands.RemoveAt(i);
i--;
}
}
if (animStartCommands.Count != animEndCommands.Count) {
Debug.LogError("Unequal number of start and end animation commands. Start Commands: " + animStartCommands.Count + " End Commands: " + animEndCommands.Count);
} else {
for (int i = 0; i < animStartCommands.Count; i++) {
DialogueCommand startCommand = animStartCommands[i];
DialogueCommand endCommand = animEndCommands[i];
tempResult.Add(new TextAnimInfo {
startIndex = startCommand.position,
endIndex = endCommand.position,
type = startCommand.textAnimValue
});
}
}
return tempResult.ToArray();
}
}
public struct TextAnimInfo {
public int startIndex;
public int endIndex;
public TextAnimationType type;
}
}

View file

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

View file

@ -11,527 +11,538 @@ using UnityEditor.SceneManagement;
using UnityEngine.EventSystems; using UnityEngine.EventSystems;
using UnityEditor.Experimental.SceneManagement; using UnityEditor.Experimental.SceneManagement;
using System; using System;
using SimpleTools.AudioManager;
using SimpleTools.DialogueSystem;
using SimpleTools.Cinemachine;
using SimpleTools.SceneManagement;
using SimpleTools.Menu;
public class ToolsEditor{ public class ToolsEditor{
[MenuItem("GameObject/Simple Tools/AudioManager", false, 10)] [MenuItem("GameObject/Simple Tools/AudioManager", false, 10)]
static void CreateAudioManager(){ static void CreateAudioManager(){
GameObject audioManager = new GameObject("AudioManager"); GameObject audioManager = new GameObject("AudioManager");
audioManager.AddComponent<AudioManager>(); audioManager.AddComponent<AudioManager>();
} }
[MenuItem("GameObject/Simple Tools/Dialogue System", false, 10)] [MenuItem("GameObject/Simple Tools/Dialogue System", false, 10)]
static void CreateDialogueSystem(){ static void CreateDialogueSystem(){
GameObject dialogueCanvas = new GameObject("DialogueCanvas"); GameObject dialogueCanvas = new GameObject("DialogueCanvas");
dialogueCanvas.AddComponent<RectTransform>(); dialogueCanvas.AddComponent<RectTransform>();
Canvas canvas = dialogueCanvas.AddComponent<Canvas>(); Canvas canvas = dialogueCanvas.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay; canvas.renderMode = RenderMode.ScreenSpaceOverlay;
dialogueCanvas.AddComponent<CanvasScaler>(); dialogueCanvas.AddComponent<CanvasScaler>();
dialogueCanvas.AddComponent<GraphicRaycaster>(); dialogueCanvas.AddComponent<GraphicRaycaster>();
GameObject text = new GameObject("TMP_Animated"); GameObject text = new GameObject("DialogueText");
text.transform.SetParent(dialogueCanvas.transform); text.transform.SetParent(dialogueCanvas.transform);
text.AddComponent<TMP_Animated>().text = "New Text"; text.AddComponent<TextMeshProUGUI>().text = "Dialogue";
text.GetComponent<RectTransform>().anchoredPosition = Vector2.zero; text.GetComponent<RectTransform>().anchoredPosition = Vector2.zero;
GameObject name = new GameObject("NameText"); GameObject name = new GameObject("NameText");
name.transform.SetParent(dialogueCanvas.transform); name.transform.SetParent(dialogueCanvas.transform);
name.AddComponent<TextMeshProUGUI>().text = "Name"; name.AddComponent<TextMeshProUGUI>().text = "Name";
name.GetComponent<RectTransform>().anchoredPosition = Vector2.up * 50f; name.GetComponent<RectTransform>().anchoredPosition = Vector2.up * 50f;
GameObject image = new GameObject("Image"); GameObject image = new GameObject("Image");
image.transform.SetParent(dialogueCanvas.transform); image.transform.SetParent(dialogueCanvas.transform);
image.AddComponent<Image>(); image.AddComponent<Image>();
image.GetComponent<RectTransform>().anchoredPosition = new Vector2(-150f, 25f); image.GetComponent<RectTransform>().anchoredPosition = new Vector2(-150f, 25f);
DialogueSystem dialogueSystem = dialogueCanvas.AddComponent<DialogueSystem>(); DialogueManager dialogueManager = dialogueCanvas.AddComponent<DialogueManager>();
dialogueSystem.nameText = name.GetComponent<TextMeshProUGUI>(); Debug.Log(dialogueManager.dialogueItems);
dialogueSystem.dialogue = text.GetComponent<TMP_Animated>(); dialogueManager.dialogueItems.textBox = text.GetComponent<TextMeshProUGUI>();
dialogueSystem.faceImage = image.GetComponent<Image>(); dialogueManager.dialogueItems.characterName = name.GetComponent<TextMeshProUGUI>();
dialogueSystem.nameField = name; dialogueManager.dialogueItems.characterImage = image.GetComponent<Image>();
} dialogueManager.dialogueItems.canvas = canvas;
//DialogueSystem dialogueSystem = dialogueCanvas.AddComponent<DialogueSystem>();
//dialogueSystem.nameText = name.GetComponent<TextMeshProUGUI>();
//dialogueSystem.dialogue = text.GetComponent<TMP_Animated>();
//dialogueSystem.faceImage = image.GetComponent<Image>();
//dialogueSystem.nameField = name;
}
[MenuItem("GameObject/Simple Tools/Camera Trigger/2D", false, 10)] [MenuItem("GameObject/Simple Tools/Camera Trigger/2D", false, 10)]
static void CreateCameraTrigger2D(){ static void CreateCameraTrigger2D(){
GameObject cameraTrigger = new GameObject("CameraTrigger2D"); GameObject cameraTrigger = new GameObject("CameraTrigger2D");
cameraTrigger.AddComponent<BoxCollider2D>(); cameraTrigger.AddComponent<BoxCollider2D>();
cameraTrigger.AddComponent<CMCameraTrigger>(); cameraTrigger.AddComponent<CMCameraTrigger>();
GameObject vCam = new GameObject("CM vcam1"); GameObject vCam = new GameObject("CM vcam1");
vCam.transform.SetParent(cameraTrigger.transform); vCam.transform.SetParent(cameraTrigger.transform);
vCam.SetActive(false); vCam.SetActive(false);
CinemachineVirtualCamera cam = vCam.AddComponent<CinemachineVirtualCamera>(); CinemachineVirtualCamera cam = vCam.AddComponent<CinemachineVirtualCamera>();
cam.m_Lens.Orthographic = true; cam.m_Lens.Orthographic = true;
} }
[MenuItem("GameObject/Simple Tools/Camera Trigger/3D", false, 10)] [MenuItem("GameObject/Simple Tools/Camera Trigger/3D", false, 10)]
static void CreateCameraTrigger3D(){ static void CreateCameraTrigger3D(){
GameObject cameraTrigger = new GameObject("CameraTrigger3D"); GameObject cameraTrigger = new GameObject("CameraTrigger3D");
cameraTrigger.AddComponent<BoxCollider>(); cameraTrigger.AddComponent<BoxCollider>();
cameraTrigger.AddComponent<CMCameraTrigger>(); cameraTrigger.AddComponent<CMCameraTrigger>();
GameObject vCam = new GameObject("CM vcam1"); GameObject vCam = new GameObject("CM vcam1");
vCam.transform.SetParent(cameraTrigger.transform); vCam.transform.SetParent(cameraTrigger.transform);
vCam.SetActive(false); vCam.SetActive(false);
CinemachineVirtualCamera cam = vCam.AddComponent<CinemachineVirtualCamera>(); CinemachineVirtualCamera cam = vCam.AddComponent<CinemachineVirtualCamera>();
cam.m_Lens.FieldOfView = 60f; cam.m_Lens.FieldOfView = 60f;
} }
#if CINEMACHINE_271_OR_NEWER #if CINEMACHINE_271_OR_NEWER
[MenuItem("GameObject/Simple Tools/ScreenShake Camera/2D", false, 10)] [MenuItem("GameObject/Simple Tools/ScreenShake Camera/2D", false, 10)]
static void CreateScreenShakeCamera2d(){ static void CreateScreenShakeCamera2d(){
GameObject screenShakeCamera = new GameObject("ScreenShakeCamera"); GameObject screenShakeCamera = new GameObject("ScreenShakeCamera");
CinemachineVirtualCamera vCam = screenShakeCamera.AddComponent<CinemachineVirtualCamera>(); CinemachineVirtualCamera vCam = screenShakeCamera.AddComponent<CinemachineVirtualCamera>();
vCam.m_Lens.ModeOverride = LensSettings.OverrideModes.Orthographic; vCam.m_Lens.ModeOverride = LensSettings.OverrideModes.Orthographic;
CinemachineBasicMultiChannelPerlin shake = vCam.AddCinemachineComponent<CinemachineBasicMultiChannelPerlin>(); CinemachineBasicMultiChannelPerlin shake = vCam.AddCinemachineComponent<CinemachineBasicMultiChannelPerlin>();
NoiseSettings noise = (NoiseSettings)AssetDatabase.LoadAssetAtPath("Packages/com.unity.cinemachine/Presets/Noise/6D Shake.asset", typeof(NoiseSettings)); NoiseSettings noise = (NoiseSettings)AssetDatabase.LoadAssetAtPath("Packages/com.unity.cinemachine/Presets/Noise/6D Shake.asset", typeof(NoiseSettings));
shake.m_NoiseProfile = noise; shake.m_NoiseProfile = noise;
shake.m_AmplitudeGain = 0f; shake.m_AmplitudeGain = 0f;
shake.m_FrequencyGain = 1f; shake.m_FrequencyGain = 1f;
} }
[MenuItem("GameObject/Simple Tools/ScreenShake Camera/3D", false, 10)] [MenuItem("GameObject/Simple Tools/ScreenShake Camera/3D", false, 10)]
static void CreateScreenShakeCamera3d(){ static void CreateScreenShakeCamera3d(){
GameObject screenShakeCamera = new GameObject("ScreenShakeCamera"); GameObject screenShakeCamera = new GameObject("ScreenShakeCamera");
CinemachineVirtualCamera vCam = screenShakeCamera.AddComponent<CinemachineVirtualCamera>(); CinemachineVirtualCamera vCam = screenShakeCamera.AddComponent<CinemachineVirtualCamera>();
vCam.m_Lens.ModeOverride = LensSettings.OverrideModes.Perspective; vCam.m_Lens.ModeOverride = LensSettings.OverrideModes.Perspective;
CinemachineBasicMultiChannelPerlin shake = vCam.AddCinemachineComponent<CinemachineBasicMultiChannelPerlin>(); CinemachineBasicMultiChannelPerlin shake = vCam.AddCinemachineComponent<CinemachineBasicMultiChannelPerlin>();
NoiseSettings noise = (NoiseSettings)AssetDatabase.LoadAssetAtPath("Packages/com.unity.cinemachine/Presets/Noise/6D Shake.asset", typeof(NoiseSettings)); NoiseSettings noise = (NoiseSettings)AssetDatabase.LoadAssetAtPath("Packages/com.unity.cinemachine/Presets/Noise/6D Shake.asset", typeof(NoiseSettings));
shake.m_NoiseProfile = noise; shake.m_NoiseProfile = noise;
shake.m_AmplitudeGain = 0f; shake.m_AmplitudeGain = 0f;
shake.m_FrequencyGain = 1f; shake.m_FrequencyGain = 1f;
} }
#else #else
[MenuItem("GameObject/Simple Tools/ScreenShake Camera", false, 10)] [MenuItem("GameObject/Simple Tools/ScreenShake Camera", false, 10)]
static void CreateScreenShakeCamera2d(){ static void CreateScreenShakeCamera2d(){
GameObject screenShakeCamera = new GameObject("ScreenShakeCamera"); GameObject screenShakeCamera = new GameObject("ScreenShakeCamera");
CinemachineVirtualCamera vCam = screenShakeCamera.AddComponent<CinemachineVirtualCamera>(); CinemachineVirtualCamera vCam = screenShakeCamera.AddComponent<CinemachineVirtualCamera>();
CinemachineBasicMultiChannelPerlin shake = vCam.AddCinemachineComponent<CinemachineBasicMultiChannelPerlin>(); CinemachineBasicMultiChannelPerlin shake = vCam.AddCinemachineComponent<CinemachineBasicMultiChannelPerlin>();
NoiseSettings noise = (NoiseSettings)AssetDatabase.LoadAssetAtPath("Packages/com.unity.cinemachine/Presets/Noise/6D Shake.asset", typeof(NoiseSettings)); NoiseSettings noise = (NoiseSettings)AssetDatabase.LoadAssetAtPath("Packages/com.unity.cinemachine/Presets/Noise/6D Shake.asset", typeof(NoiseSettings));
shake.m_NoiseProfile = noise; shake.m_NoiseProfile = noise;
shake.m_AmplitudeGain = 0f; shake.m_AmplitudeGain = 0f;
shake.m_FrequencyGain = 1f; shake.m_FrequencyGain = 1f;
} }
#endif #endif
[MenuItem("Assets/Create/Simple Tools/Create Loading Scene")] [MenuItem("Assets/Create/Simple Tools/Create Loading Scene")]
[MenuItem("Simple Tools/Create Loading Scene")] [MenuItem("Simple Tools/Create Loading Scene")]
static void CreateLoadingScene(){ static void CreateLoadingScene(){
EditorSceneManager.SaveOpenScenes(); EditorSceneManager.SaveOpenScenes();
Scene loadingScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects); Scene loadingScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects);
loadingScene.name = "Loading"; loadingScene.name = "Loading";
GameObject loaderCallback = new GameObject("LoaderCallback"); GameObject loaderCallback = new GameObject("LoaderCallback");
loaderCallback.AddComponent<LoaderCallback>(); loaderCallback.AddComponent<LoaderCallback>();
GameObject canvasObj = new GameObject("Canvas"); GameObject canvasObj = new GameObject("Canvas");
Canvas canvas = canvasObj.AddComponent<Canvas>(); Canvas canvas = canvasObj.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay; canvas.renderMode = RenderMode.ScreenSpaceOverlay;
CanvasScaler canvasScaler = canvasObj.AddComponent<CanvasScaler>(); CanvasScaler canvasScaler = canvasObj.AddComponent<CanvasScaler>();
canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize; canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
canvasScaler.referenceResolution = new Vector2Int(951, 535); canvasScaler.referenceResolution = new Vector2Int(951, 535);
canvasScaler.matchWidthOrHeight = 1f; canvasScaler.matchWidthOrHeight = 1f;
canvasObj.AddComponent<GraphicRaycaster>(); canvasObj.AddComponent<GraphicRaycaster>();
TextMeshProUGUI loadingText = new GameObject("LoadingText").AddComponent<TextMeshProUGUI>(); TextMeshProUGUI loadingText = new GameObject("LoadingText").AddComponent<TextMeshProUGUI>();
loadingText.transform.SetParent(canvasObj.transform); loadingText.transform.SetParent(canvasObj.transform);
RectTransform loadingTextTransform = loadingText.GetComponent<RectTransform>(); RectTransform loadingTextTransform = loadingText.GetComponent<RectTransform>();
loadingTextTransform.anchoredPosition = new Vector2Int(-333, -212); loadingTextTransform.anchoredPosition = new Vector2Int(-333, -212);
loadingTextTransform.sizeDelta = new Vector2Int(237, 52); loadingTextTransform.sizeDelta = new Vector2Int(237, 52);
loadingText.text = "LOADING..."; loadingText.text = "LOADING...";
Image bg = new GameObject("bg").AddComponent<Image>(); Image bg = new GameObject("bg").AddComponent<Image>();
bg.transform.SetParent(canvasObj.transform); bg.transform.SetParent(canvasObj.transform);
RectTransform bgTransform = bg.GetComponent<RectTransform>(); RectTransform bgTransform = bg.GetComponent<RectTransform>();
bgTransform.anchoredPosition = new Vector2Int(0, -235); bgTransform.anchoredPosition = new Vector2Int(0, -235);
bgTransform.sizeDelta = new Vector2Int(900, 20); bgTransform.sizeDelta = new Vector2Int(900, 20);
bg.color = new Color(36f / 255f, 36f / 255f, 36f / 255f); bg.color = new Color(36f / 255f, 36f / 255f, 36f / 255f);
Image progressBar = new GameObject("ProgressBar").AddComponent<Image>(); Image progressBar = new GameObject("ProgressBar").AddComponent<Image>();
progressBar.transform.SetParent(bg.transform); progressBar.transform.SetParent(bg.transform);
RectTransform progressBarTransform = progressBar.GetComponent<RectTransform>(); RectTransform progressBarTransform = progressBar.GetComponent<RectTransform>();
progressBarTransform.anchoredPosition = Vector2.zero; progressBarTransform.anchoredPosition = Vector2.zero;
progressBarTransform.sizeDelta = new Vector2Int(900, 20); progressBarTransform.sizeDelta = new Vector2Int(900, 20);
progressBar.sprite = (Sprite)AssetDatabase.LoadAssetAtPath("Packages/com.geri.simpletools/Simple Tools/Editor/Square.png", typeof(Sprite)); progressBar.sprite = (Sprite)AssetDatabase.LoadAssetAtPath("Packages/com.geri.simpletools/Simple Tools/Editor/Square.png", typeof(Sprite));
progressBar.type = Image.Type.Filled; progressBar.type = Image.Type.Filled;
progressBar.fillMethod = Image.FillMethod.Horizontal; progressBar.fillMethod = Image.FillMethod.Horizontal;
progressBar.fillOrigin = (int)Image.OriginHorizontal.Left; progressBar.fillOrigin = (int)Image.OriginHorizontal.Left;
progressBar.fillAmount = 1f; progressBar.fillAmount = 1f;
progressBar.gameObject.AddComponent<LoadingProgressBar>(); progressBar.gameObject.AddComponent<LoadingProgressBar>();
} }
#if UNITY_2019_3_OR_NEWER #if UNITY_2019_3_OR_NEWER
[MenuItem("Assets/Create/Simple Tools/Create Menu Scene")] [MenuItem("Assets/Create/Simple Tools/Create Menu Scene")]
[MenuItem("Simple Tools/Create Menu Scene")] [MenuItem("Simple Tools/Create Menu Scene")]
static void CreateMenuScene(){ static void CreateMenuScene(){
EditorSceneManager.SaveOpenScenes(); EditorSceneManager.SaveOpenScenes();
Scene menuScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects); Scene menuScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects);
menuScene.name = "Menu"; menuScene.name = "Menu";
GameObject canvasObj = new GameObject("Canvas"); GameObject canvasObj = new GameObject("Canvas");
Canvas canvas = canvasObj.AddComponent<Canvas>(); Canvas canvas = canvasObj.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay; canvas.renderMode = RenderMode.ScreenSpaceOverlay;
CreateEventSystem(false, null); CreateEventSystem(false, null);
CanvasScaler canvasScaler = canvasObj.AddComponent<CanvasScaler>(); CanvasScaler canvasScaler = canvasObj.AddComponent<CanvasScaler>();
canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize; canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
canvasScaler.referenceResolution = new Vector2Int(951, 535); canvasScaler.referenceResolution = new Vector2Int(951, 535);
canvasScaler.matchWidthOrHeight = 1f; canvasScaler.matchWidthOrHeight = 1f;
canvasObj.AddComponent<GraphicRaycaster>(); canvasObj.AddComponent<GraphicRaycaster>();
GameObject qualityDropdown = TMP_DefaultControls.CreateDropdown(GetStandardResources()); GameObject qualityDropdown = TMP_DefaultControls.CreateDropdown(GetStandardResources());
qualityDropdown.transform.SetParent(canvasObj.transform); qualityDropdown.transform.SetParent(canvasObj.transform);
RectTransform qualityRectTransform = qualityDropdown.GetComponent<RectTransform>(); RectTransform qualityRectTransform = qualityDropdown.GetComponent<RectTransform>();
qualityRectTransform.anchoredPosition = Vector2.up * 15f; qualityRectTransform.anchoredPosition = Vector2.up * 15f;
qualityDropdown.name = "QualityDropdown"; qualityDropdown.name = "QualityDropdown";
GameObject resolutionDropdown = TMP_DefaultControls.CreateDropdown(GetStandardResources()); GameObject resolutionDropdown = TMP_DefaultControls.CreateDropdown(GetStandardResources());
resolutionDropdown.transform.SetParent(canvasObj.transform); resolutionDropdown.transform.SetParent(canvasObj.transform);
RectTransform resolutionRectTransform = resolutionDropdown.GetComponent<RectTransform>(); RectTransform resolutionRectTransform = resolutionDropdown.GetComponent<RectTransform>();
resolutionRectTransform.anchoredPosition = Vector2.down * 15f; resolutionRectTransform.anchoredPosition = Vector2.down * 15f;
resolutionDropdown.name = "ResolutionDropdown"; resolutionDropdown.name = "ResolutionDropdown";
GameObject musicSlider; GameObject musicSlider;
using (new FactorySwapToEditor()) using (new FactorySwapToEditor())
musicSlider = DefaultControls.CreateSlider(GetStandardUIResources()); musicSlider = DefaultControls.CreateSlider(GetStandardUIResources());
musicSlider.transform.SetParent(canvasObj.transform); musicSlider.transform.SetParent(canvasObj.transform);
RectTransform musicRectTransform = musicSlider.GetComponent<RectTransform>(); RectTransform musicRectTransform = musicSlider.GetComponent<RectTransform>();
musicRectTransform.anchoredPosition = Vector2.down * 40f; musicRectTransform.anchoredPosition = Vector2.down * 40f;
musicSlider.name = "MusicSlider"; musicSlider.name = "MusicSlider";
GameObject sfxSlider; GameObject sfxSlider;
using (new FactorySwapToEditor()) using (new FactorySwapToEditor())
sfxSlider = DefaultControls.CreateSlider(GetStandardUIResources()); sfxSlider = DefaultControls.CreateSlider(GetStandardUIResources());
sfxSlider.transform.SetParent(canvasObj.transform); sfxSlider.transform.SetParent(canvasObj.transform);
RectTransform sfxRectTransform = sfxSlider.GetComponent<RectTransform>(); RectTransform sfxRectTransform = sfxSlider.GetComponent<RectTransform>();
sfxRectTransform.anchoredPosition = Vector2.down * 60; sfxRectTransform.anchoredPosition = Vector2.down * 60;
sfxSlider.name = "MusicSlider"; sfxSlider.name = "MusicSlider";
GameObject playButton = TMP_DefaultControls.CreateButton(GetStandardResources()); GameObject playButton = TMP_DefaultControls.CreateButton(GetStandardResources());
playButton.transform.SetParent(canvasObj.transform); playButton.transform.SetParent(canvasObj.transform);
TMP_Text playTextComponent = playButton.GetComponentInChildren<TMP_Text>(); TMP_Text playTextComponent = playButton.GetComponentInChildren<TMP_Text>();
playTextComponent.fontSize = 24; playTextComponent.fontSize = 24;
playTextComponent.text = "PLAY"; playTextComponent.text = "PLAY";
RectTransform playRectTransform = playButton.GetComponent<RectTransform>(); RectTransform playRectTransform = playButton.GetComponent<RectTransform>();
playRectTransform.anchoredPosition = Vector2.up * 45f; playRectTransform.anchoredPosition = Vector2.up * 45f;
playButton.name = "PlayButton"; playButton.name = "PlayButton";
GameObject quitButton = TMP_DefaultControls.CreateButton(GetStandardResources()); GameObject quitButton = TMP_DefaultControls.CreateButton(GetStandardResources());
quitButton.transform.SetParent(canvasObj.transform); quitButton.transform.SetParent(canvasObj.transform);
TMP_Text quitTextComponent = quitButton.GetComponentInChildren<TMP_Text>(); TMP_Text quitTextComponent = quitButton.GetComponentInChildren<TMP_Text>();
quitTextComponent.fontSize = 24; quitTextComponent.fontSize = 24;
quitTextComponent.text = "QUIT"; quitTextComponent.text = "QUIT";
RectTransform quitRectTransform = quitButton.GetComponent<RectTransform>(); RectTransform quitRectTransform = quitButton.GetComponent<RectTransform>();
quitRectTransform.anchoredPosition = Vector2.down * 85f; quitRectTransform.anchoredPosition = Vector2.down * 85f;
quitButton.name = "QuitButton"; quitButton.name = "QuitButton";
MenuController menuController = canvasObj.AddComponent<MenuController>(); MenuController menuController = canvasObj.AddComponent<MenuController>();
Slider sliderMusic = menuController.musicSlider = musicSlider.GetComponent<Slider>(); Slider sliderMusic = menuController.musicSlider = musicSlider.GetComponent<Slider>();
Slider sliderSfx = menuController.sfxSlider = sfxSlider.GetComponent<Slider>(); Slider sliderSfx = menuController.sfxSlider = sfxSlider.GetComponent<Slider>();
TMP_Dropdown dropdownQuality = menuController.qualityDropdown = qualityDropdown.GetComponent<TMP_Dropdown>(); TMP_Dropdown dropdownQuality = menuController.qualityDropdown = qualityDropdown.GetComponent<TMP_Dropdown>();
TMP_Dropdown dropdownResolution = menuController.resolutionDropdown = resolutionDropdown.GetComponent<TMP_Dropdown>(); TMP_Dropdown dropdownResolution = menuController.resolutionDropdown = resolutionDropdown.GetComponent<TMP_Dropdown>();
sliderMusic.onValueChanged.AddListener(menuController.SetMusicVolume); sliderMusic.onValueChanged.AddListener(menuController.SetMusicVolume);
sliderSfx.onValueChanged.AddListener(menuController.SetSfxVolume); sliderSfx.onValueChanged.AddListener(menuController.SetSfxVolume);
dropdownQuality.onValueChanged.AddListener(menuController.SetQuality); dropdownQuality.onValueChanged.AddListener(menuController.SetQuality);
dropdownResolution.onValueChanged.AddListener(menuController.SetResolution); dropdownResolution.onValueChanged.AddListener(menuController.SetResolution);
playButton.GetComponent<Button>().onClick.AddListener(menuController.Play); playButton.GetComponent<Button>().onClick.AddListener(menuController.Play);
quitButton.GetComponent<Button>().onClick.AddListener(menuController.Quit); quitButton.GetComponent<Button>().onClick.AddListener(menuController.Quit);
} }
#region CreateUISettings #region CreateUISettings
const string kUILayerName = "UI"; const string kUILayerName = "UI";
const string kStandardSpritePath = "UI/Skin/UISprite.psd"; const string kStandardSpritePath = "UI/Skin/UISprite.psd";
const string kBackgroundSpritePath = "UI/Skin/Background.psd"; const string kBackgroundSpritePath = "UI/Skin/Background.psd";
const string kInputFieldBackgroundPath = "UI/Skin/InputFieldBackground.psd"; const string kInputFieldBackgroundPath = "UI/Skin/InputFieldBackground.psd";
const string kKnobPath = "UI/Skin/Knob.psd"; const string kKnobPath = "UI/Skin/Knob.psd";
const string kCheckmarkPath = "UI/Skin/Checkmark.psd"; const string kCheckmarkPath = "UI/Skin/Checkmark.psd";
const string kDropdownArrowPath = "UI/Skin/DropdownArrow.psd"; const string kDropdownArrowPath = "UI/Skin/DropdownArrow.psd";
const string kMaskPath = "UI/Skin/UIMask.psd"; const string kMaskPath = "UI/Skin/UIMask.psd";
static TMP_DefaultControls.Resources s_StandardResources; static TMP_DefaultControls.Resources s_StandardResources;
static TMP_DefaultControls.Resources GetStandardResources(){ static TMP_DefaultControls.Resources GetStandardResources(){
if (s_StandardResources.standard == null){ if (s_StandardResources.standard == null){
s_StandardResources.standard = AssetDatabase.GetBuiltinExtraResource<Sprite>(kStandardSpritePath); s_StandardResources.standard = AssetDatabase.GetBuiltinExtraResource<Sprite>(kStandardSpritePath);
s_StandardResources.background = AssetDatabase.GetBuiltinExtraResource<Sprite>(kBackgroundSpritePath); s_StandardResources.background = AssetDatabase.GetBuiltinExtraResource<Sprite>(kBackgroundSpritePath);
s_StandardResources.inputField = AssetDatabase.GetBuiltinExtraResource<Sprite>(kInputFieldBackgroundPath); s_StandardResources.inputField = AssetDatabase.GetBuiltinExtraResource<Sprite>(kInputFieldBackgroundPath);
s_StandardResources.knob = AssetDatabase.GetBuiltinExtraResource<Sprite>(kKnobPath); s_StandardResources.knob = AssetDatabase.GetBuiltinExtraResource<Sprite>(kKnobPath);
s_StandardResources.checkmark = AssetDatabase.GetBuiltinExtraResource<Sprite>(kCheckmarkPath); s_StandardResources.checkmark = AssetDatabase.GetBuiltinExtraResource<Sprite>(kCheckmarkPath);
s_StandardResources.dropdown = AssetDatabase.GetBuiltinExtraResource<Sprite>(kDropdownArrowPath); s_StandardResources.dropdown = AssetDatabase.GetBuiltinExtraResource<Sprite>(kDropdownArrowPath);
s_StandardResources.mask = AssetDatabase.GetBuiltinExtraResource<Sprite>(kMaskPath); s_StandardResources.mask = AssetDatabase.GetBuiltinExtraResource<Sprite>(kMaskPath);
} }
return s_StandardResources; return s_StandardResources;
} }
static void SetPositionVisibleinSceneView(RectTransform canvasRTransform, RectTransform itemTransform){ static void SetPositionVisibleinSceneView(RectTransform canvasRTransform, RectTransform itemTransform){
// Find the best scene view // Find the best scene view
SceneView sceneView = SceneView.lastActiveSceneView; SceneView sceneView = SceneView.lastActiveSceneView;
if (sceneView == null && SceneView.sceneViews.Count > 0) if (sceneView == null && SceneView.sceneViews.Count > 0)
sceneView = SceneView.sceneViews[0] as SceneView; sceneView = SceneView.sceneViews[0] as SceneView;
// Couldn't find a SceneView. Don't set position. // Couldn't find a SceneView. Don't set position.
if (sceneView == null || sceneView.camera == null) if (sceneView == null || sceneView.camera == null)
return; return;
// Create world space Plane from canvas position. // Create world space Plane from canvas position.
Camera camera = sceneView.camera; Camera camera = sceneView.camera;
Vector3 position = Vector3.zero; Vector3 position = Vector3.zero;
Vector2 localPlanePosition; Vector2 localPlanePosition;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRTransform, new Vector2(camera.pixelWidth / 2, camera.pixelHeight / 2), camera, out localPlanePosition)){ if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRTransform, new Vector2(camera.pixelWidth / 2, camera.pixelHeight / 2), camera, out localPlanePosition)){
// Adjust for canvas pivot // Adjust for canvas pivot
localPlanePosition.x = localPlanePosition.x + canvasRTransform.sizeDelta.x * canvasRTransform.pivot.x; localPlanePosition.x = localPlanePosition.x + canvasRTransform.sizeDelta.x * canvasRTransform.pivot.x;
localPlanePosition.y = localPlanePosition.y + canvasRTransform.sizeDelta.y * canvasRTransform.pivot.y; localPlanePosition.y = localPlanePosition.y + canvasRTransform.sizeDelta.y * canvasRTransform.pivot.y;
localPlanePosition.x = Mathf.Clamp(localPlanePosition.x, 0, canvasRTransform.sizeDelta.x); localPlanePosition.x = Mathf.Clamp(localPlanePosition.x, 0, canvasRTransform.sizeDelta.x);
localPlanePosition.y = Mathf.Clamp(localPlanePosition.y, 0, canvasRTransform.sizeDelta.y); localPlanePosition.y = Mathf.Clamp(localPlanePosition.y, 0, canvasRTransform.sizeDelta.y);
// Adjust for anchoring // Adjust for anchoring
position.x = localPlanePosition.x - canvasRTransform.sizeDelta.x * itemTransform.anchorMin.x; position.x = localPlanePosition.x - canvasRTransform.sizeDelta.x * itemTransform.anchorMin.x;
position.y = localPlanePosition.y - canvasRTransform.sizeDelta.y * itemTransform.anchorMin.y; position.y = localPlanePosition.y - canvasRTransform.sizeDelta.y * itemTransform.anchorMin.y;
Vector3 minLocalPosition; Vector3 minLocalPosition;
minLocalPosition.x = canvasRTransform.sizeDelta.x * (0 - canvasRTransform.pivot.x) + itemTransform.sizeDelta.x * itemTransform.pivot.x; minLocalPosition.x = canvasRTransform.sizeDelta.x * (0 - canvasRTransform.pivot.x) + itemTransform.sizeDelta.x * itemTransform.pivot.x;
minLocalPosition.y = canvasRTransform.sizeDelta.y * (0 - canvasRTransform.pivot.y) + itemTransform.sizeDelta.y * itemTransform.pivot.y; minLocalPosition.y = canvasRTransform.sizeDelta.y * (0 - canvasRTransform.pivot.y) + itemTransform.sizeDelta.y * itemTransform.pivot.y;
Vector3 maxLocalPosition; Vector3 maxLocalPosition;
maxLocalPosition.x = canvasRTransform.sizeDelta.x * (1 - canvasRTransform.pivot.x) - itemTransform.sizeDelta.x * itemTransform.pivot.x; maxLocalPosition.x = canvasRTransform.sizeDelta.x * (1 - canvasRTransform.pivot.x) - itemTransform.sizeDelta.x * itemTransform.pivot.x;
maxLocalPosition.y = canvasRTransform.sizeDelta.y * (1 - canvasRTransform.pivot.y) - itemTransform.sizeDelta.y * itemTransform.pivot.y; maxLocalPosition.y = canvasRTransform.sizeDelta.y * (1 - canvasRTransform.pivot.y) - itemTransform.sizeDelta.y * itemTransform.pivot.y;
position.x = Mathf.Clamp(position.x, minLocalPosition.x, maxLocalPosition.x); position.x = Mathf.Clamp(position.x, minLocalPosition.x, maxLocalPosition.x);
position.y = Mathf.Clamp(position.y, minLocalPosition.y, maxLocalPosition.y); position.y = Mathf.Clamp(position.y, minLocalPosition.y, maxLocalPosition.y);
} }
itemTransform.anchoredPosition = position; itemTransform.anchoredPosition = position;
itemTransform.localRotation = Quaternion.identity; itemTransform.localRotation = Quaternion.identity;
itemTransform.localScale = Vector3.one; itemTransform.localScale = Vector3.one;
} }
static GameObject CreateNewUI(){ static GameObject CreateNewUI(){
// Root for the UI // Root for the UI
var root = new GameObject("Canvas"); var root = new GameObject("Canvas");
root.layer = LayerMask.NameToLayer(kUILayerName); root.layer = LayerMask.NameToLayer(kUILayerName);
Canvas canvas = root.AddComponent<Canvas>(); Canvas canvas = root.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay; canvas.renderMode = RenderMode.ScreenSpaceOverlay;
root.AddComponent<CanvasScaler>(); root.AddComponent<CanvasScaler>();
root.AddComponent<GraphicRaycaster>(); root.AddComponent<GraphicRaycaster>();
// Works for all stages. // Works for all stages.
StageUtility.PlaceGameObjectInCurrentStage(root); StageUtility.PlaceGameObjectInCurrentStage(root);
bool customScene = false; bool customScene = false;
PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage(); PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage != null){ if (prefabStage != null){
root.transform.SetParent(prefabStage.prefabContentsRoot.transform, false); root.transform.SetParent(prefabStage.prefabContentsRoot.transform, false);
customScene = true; customScene = true;
} }
Undo.RegisterCreatedObjectUndo(root, "Create " + root.name); Undo.RegisterCreatedObjectUndo(root, "Create " + root.name);
// If there is no event system add one... // If there is no event system add one...
// No need to place event system in custom scene as these are temporary anyway. // No need to place event system in custom scene as these are temporary anyway.
// It can be argued for or against placing it in the user scenes, // It can be argued for or against placing it in the user scenes,
// but let's not modify scene user is not currently looking at. // but let's not modify scene user is not currently looking at.
if (!customScene) if (!customScene)
CreateEventSystem(false); CreateEventSystem(false);
return root; return root;
} }
static void CreateEventSystem(bool select){ static void CreateEventSystem(bool select){
CreateEventSystem(select, null); CreateEventSystem(select, null);
} }
static void CreateEventSystem(bool select, GameObject parent){ static void CreateEventSystem(bool select, GameObject parent){
var esys = UnityEngine.Object.FindObjectOfType<EventSystem>(); var esys = UnityEngine.Object.FindObjectOfType<EventSystem>();
if (esys == null){ if (esys == null){
var eventSystem = new GameObject("EventSystem"); var eventSystem = new GameObject("EventSystem");
GameObjectUtility.SetParentAndAlign(eventSystem, parent); GameObjectUtility.SetParentAndAlign(eventSystem, parent);
esys = eventSystem.AddComponent<EventSystem>(); esys = eventSystem.AddComponent<EventSystem>();
eventSystem.AddComponent<StandaloneInputModule>(); eventSystem.AddComponent<StandaloneInputModule>();
Undo.RegisterCreatedObjectUndo(eventSystem, "Create " + eventSystem.name); Undo.RegisterCreatedObjectUndo(eventSystem, "Create " + eventSystem.name);
} }
if (select && esys != null){ if (select && esys != null){
Selection.activeGameObject = esys.gameObject; Selection.activeGameObject = esys.gameObject;
} }
} }
// Helper function that returns a Canvas GameObject; preferably a parent of the selection, or other existing Canvas. // Helper function that returns a Canvas GameObject; preferably a parent of the selection, or other existing Canvas.
static GameObject GetOrCreateCanvasGameObject(){ static GameObject GetOrCreateCanvasGameObject(){
GameObject selectedGo = Selection.activeGameObject; GameObject selectedGo = Selection.activeGameObject;
// Try to find a gameobject that is the selected GO or one if its parents. // Try to find a gameobject that is the selected GO or one if its parents.
Canvas canvas = (selectedGo != null) ? selectedGo.GetComponentInParent<Canvas>() : null; Canvas canvas = (selectedGo != null) ? selectedGo.GetComponentInParent<Canvas>() : null;
if (IsValidCanvas(canvas)) if (IsValidCanvas(canvas))
return canvas.gameObject; return canvas.gameObject;
// No canvas in selection or its parents? Then use any valid canvas. // No canvas in selection or its parents? Then use any valid canvas.
// We have to find all loaded Canvases, not just the ones in main scenes. // We have to find all loaded Canvases, not just the ones in main scenes.
Canvas[] canvasArray = StageUtility.GetCurrentStageHandle().FindComponentsOfType<Canvas>(); Canvas[] canvasArray = StageUtility.GetCurrentStageHandle().FindComponentsOfType<Canvas>();
for (int i = 0; i < canvasArray.Length; i++) for (int i = 0; i < canvasArray.Length; i++)
if (IsValidCanvas(canvasArray[i])) if (IsValidCanvas(canvasArray[i]))
return canvasArray[i].gameObject; return canvasArray[i].gameObject;
// No canvas in the scene at all? Then create a new one. // No canvas in the scene at all? Then create a new one.
return CreateNewUI(); return CreateNewUI();
} }
static bool IsValidCanvas(Canvas canvas){ static bool IsValidCanvas(Canvas canvas){
if (canvas == null || !canvas.gameObject.activeInHierarchy) if (canvas == null || !canvas.gameObject.activeInHierarchy)
return false; return false;
// It's important that the non-editable canvas from a prefab scene won't be rejected, // It's important that the non-editable canvas from a prefab scene won't be rejected,
// but canvases not visible in the Hierarchy at all do. Don't check for HideAndDontSave. // but canvases not visible in the Hierarchy at all do. Don't check for HideAndDontSave.
if (EditorUtility.IsPersistent(canvas) || (canvas.hideFlags & HideFlags.HideInHierarchy) != 0) if (EditorUtility.IsPersistent(canvas) || (canvas.hideFlags & HideFlags.HideInHierarchy) != 0)
return false; return false;
if (StageUtility.GetStageHandle(canvas.gameObject) != StageUtility.GetCurrentStageHandle()) if (StageUtility.GetStageHandle(canvas.gameObject) != StageUtility.GetCurrentStageHandle())
return false; return false;
return true; return true;
} }
class FactorySwapToEditor : IDisposable{ class FactorySwapToEditor : IDisposable{
DefaultControls.IFactoryControls factory; DefaultControls.IFactoryControls factory;
public FactorySwapToEditor(){ public FactorySwapToEditor(){
factory = DefaultControls.factory; factory = DefaultControls.factory;
DefaultControls.factory = DefaultEditorFactory.Default; DefaultControls.factory = DefaultEditorFactory.Default;
} }
public void Dispose(){ public void Dispose(){
DefaultControls.factory = factory; DefaultControls.factory = factory;
} }
} }
const string kStandardSpritePathDefault = "UI/Skin/UISprite.psd"; const string kStandardSpritePathDefault = "UI/Skin/UISprite.psd";
const string kBackgroundSpritePathDefault = "UI/Skin/Background.psd"; const string kBackgroundSpritePathDefault = "UI/Skin/Background.psd";
const string kInputFieldBackgroundPathDefault = "UI/Skin/InputFieldBackground.psd"; const string kInputFieldBackgroundPathDefault = "UI/Skin/InputFieldBackground.psd";
const string kKnobPathDefault = "UI/Skin/Knob.psd"; const string kKnobPathDefault = "UI/Skin/Knob.psd";
const string kCheckmarkPathDefault = "UI/Skin/Checkmark.psd"; const string kCheckmarkPathDefault = "UI/Skin/Checkmark.psd";
const string kDropdownArrowPathDefault = "UI/Skin/DropdownArrow.psd"; const string kDropdownArrowPathDefault = "UI/Skin/DropdownArrow.psd";
const string kMaskPathDefault = "UI/Skin/UIMask.psd"; const string kMaskPathDefault = "UI/Skin/UIMask.psd";
static DefaultControls.Resources s_StandardResourcesDefault; static DefaultControls.Resources s_StandardResourcesDefault;
static DefaultControls.Resources GetStandardUIResources(){ static DefaultControls.Resources GetStandardUIResources(){
if (s_StandardResourcesDefault.standard == null){ if (s_StandardResourcesDefault.standard == null){
s_StandardResourcesDefault.standard = AssetDatabase.GetBuiltinExtraResource<Sprite>(kStandardSpritePathDefault); s_StandardResourcesDefault.standard = AssetDatabase.GetBuiltinExtraResource<Sprite>(kStandardSpritePathDefault);
s_StandardResourcesDefault.background = AssetDatabase.GetBuiltinExtraResource<Sprite>(kBackgroundSpritePathDefault); s_StandardResourcesDefault.background = AssetDatabase.GetBuiltinExtraResource<Sprite>(kBackgroundSpritePathDefault);
s_StandardResourcesDefault.inputField = AssetDatabase.GetBuiltinExtraResource<Sprite>(kInputFieldBackgroundPathDefault); s_StandardResourcesDefault.inputField = AssetDatabase.GetBuiltinExtraResource<Sprite>(kInputFieldBackgroundPathDefault);
s_StandardResourcesDefault.knob = AssetDatabase.GetBuiltinExtraResource<Sprite>(kKnobPathDefault); s_StandardResourcesDefault.knob = AssetDatabase.GetBuiltinExtraResource<Sprite>(kKnobPathDefault);
s_StandardResourcesDefault.checkmark = AssetDatabase.GetBuiltinExtraResource<Sprite>(kCheckmarkPathDefault); s_StandardResourcesDefault.checkmark = AssetDatabase.GetBuiltinExtraResource<Sprite>(kCheckmarkPathDefault);
s_StandardResourcesDefault.dropdown = AssetDatabase.GetBuiltinExtraResource<Sprite>(kDropdownArrowPathDefault); s_StandardResourcesDefault.dropdown = AssetDatabase.GetBuiltinExtraResource<Sprite>(kDropdownArrowPathDefault);
s_StandardResourcesDefault.mask = AssetDatabase.GetBuiltinExtraResource<Sprite>(kMaskPathDefault); s_StandardResourcesDefault.mask = AssetDatabase.GetBuiltinExtraResource<Sprite>(kMaskPathDefault);
} }
return s_StandardResourcesDefault; return s_StandardResourcesDefault;
} }
static void PlaceUIElementRoot(GameObject element, MenuCommand menuCommand){ static void PlaceUIElementRoot(GameObject element, MenuCommand menuCommand){
GameObject parent = menuCommand.context as GameObject; GameObject parent = menuCommand.context as GameObject;
bool explicitParentChoice = true; bool explicitParentChoice = true;
if (parent == null){ if (parent == null){
parent = GetOrCreateCanvasGameObject(); parent = GetOrCreateCanvasGameObject();
explicitParentChoice = false; explicitParentChoice = false;
// If in Prefab Mode, Canvas has to be part of Prefab contents, // If in Prefab Mode, Canvas has to be part of Prefab contents,
// otherwise use Prefab root instead. // otherwise use Prefab root instead.
PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage(); PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage != null && !prefabStage.IsPartOfPrefabContents(parent)) if (prefabStage != null && !prefabStage.IsPartOfPrefabContents(parent))
parent = prefabStage.prefabContentsRoot; parent = prefabStage.prefabContentsRoot;
} }
if (parent.GetComponentsInParent<Canvas>(true).Length == 0){ if (parent.GetComponentsInParent<Canvas>(true).Length == 0){
// Create canvas under context GameObject, // Create canvas under context GameObject,
// and make that be the parent which UI element is added under. // and make that be the parent which UI element is added under.
GameObject canvas = CreateNewUIDefault(); GameObject canvas = CreateNewUIDefault();
Undo.SetTransformParent(canvas.transform, parent.transform, ""); Undo.SetTransformParent(canvas.transform, parent.transform, "");
parent = canvas; parent = canvas;
} }
GameObjectUtility.EnsureUniqueNameForSibling(element); GameObjectUtility.EnsureUniqueNameForSibling(element);
SetParentAndAlign(element, parent); SetParentAndAlign(element, parent);
if (!explicitParentChoice) // not a context click, so center in sceneview if (!explicitParentChoice) // not a context click, so center in sceneview
SetPositionVisibleinSceneView(parent.GetComponent<RectTransform>(), element.GetComponent<RectTransform>()); SetPositionVisibleinSceneView(parent.GetComponent<RectTransform>(), element.GetComponent<RectTransform>());
// This call ensure any change made to created Objects after they where registered will be part of the Undo. // This call ensure any change made to created Objects after they where registered will be part of the Undo.
Undo.RegisterFullObjectHierarchyUndo(parent == null ? element : parent, ""); Undo.RegisterFullObjectHierarchyUndo(parent == null ? element : parent, "");
// We have to fix up the undo name since the name of the object was only known after reparenting it. // We have to fix up the undo name since the name of the object was only known after reparenting it.
Undo.SetCurrentGroupName("Create " + element.name); Undo.SetCurrentGroupName("Create " + element.name);
Selection.activeGameObject = element; Selection.activeGameObject = element;
} }
static GameObject CreateNewUIDefault(){ static GameObject CreateNewUIDefault(){
// Root for the UI // Root for the UI
var root = ObjectFactory.CreateGameObject("Canvas", typeof(Canvas), typeof(CanvasScaler), typeof(GraphicRaycaster)); var root = ObjectFactory.CreateGameObject("Canvas", typeof(Canvas), typeof(CanvasScaler), typeof(GraphicRaycaster));
root.layer = LayerMask.NameToLayer(kUILayerName); root.layer = LayerMask.NameToLayer(kUILayerName);
Canvas canvas = root.GetComponent<Canvas>(); Canvas canvas = root.GetComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay; canvas.renderMode = RenderMode.ScreenSpaceOverlay;
// Works for all stages. // Works for all stages.
StageUtility.PlaceGameObjectInCurrentStage(root); StageUtility.PlaceGameObjectInCurrentStage(root);
bool customScene = false; bool customScene = false;
PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage(); PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage != null){ if (prefabStage != null){
Undo.SetTransformParent(root.transform, prefabStage.prefabContentsRoot.transform, ""); Undo.SetTransformParent(root.transform, prefabStage.prefabContentsRoot.transform, "");
customScene = true; customScene = true;
} }
Undo.SetCurrentGroupName("Create " + root.name); Undo.SetCurrentGroupName("Create " + root.name);
// If there is no event system add one... // If there is no event system add one...
// No need to place event system in custom scene as these are temporary anyway. // No need to place event system in custom scene as these are temporary anyway.
// It can be argued for or against placing it in the user scenes, // It can be argued for or against placing it in the user scenes,
// but let's not modify scene user is not currently looking at. // but let's not modify scene user is not currently looking at.
if (!customScene) if (!customScene)
CreateEventSystem(false); CreateEventSystem(false);
return root; return root;
} }
static void SetParentAndAlign(GameObject child, GameObject parent){ static void SetParentAndAlign(GameObject child, GameObject parent){
if (parent == null) if (parent == null)
return; return;
Undo.SetTransformParent(child.transform, parent.transform, ""); Undo.SetTransformParent(child.transform, parent.transform, "");
RectTransform rectTransform = child.transform as RectTransform; RectTransform rectTransform = child.transform as RectTransform;
if (rectTransform){ if (rectTransform){
rectTransform.anchoredPosition = Vector2.zero; rectTransform.anchoredPosition = Vector2.zero;
Vector3 localPosition = rectTransform.localPosition; Vector3 localPosition = rectTransform.localPosition;
localPosition.z = 0; localPosition.z = 0;
rectTransform.localPosition = localPosition; rectTransform.localPosition = localPosition;
}else{ }else{
child.transform.localPosition = Vector3.zero; child.transform.localPosition = Vector3.zero;
} }
child.transform.localRotation = Quaternion.identity; child.transform.localRotation = Quaternion.identity;
child.transform.localScale = Vector3.one; child.transform.localScale = Vector3.one;
SetLayerRecursively(child, parent.layer); SetLayerRecursively(child, parent.layer);
} }
static void SetLayerRecursively(GameObject go, int layer){ static void SetLayerRecursively(GameObject go, int layer){
go.layer = layer; go.layer = layer;
Transform t = go.transform; Transform t = go.transform;
for (int i = 0; i < t.childCount; i++) for (int i = 0; i < t.childCount; i++)
SetLayerRecursively(t.GetChild(i).gameObject, layer); SetLayerRecursively(t.GetChild(i).gameObject, layer);
} }
class DefaultEditorFactory : DefaultControls.IFactoryControls{ class DefaultEditorFactory : DefaultControls.IFactoryControls{
public static DefaultEditorFactory Default = new DefaultEditorFactory(); public static DefaultEditorFactory Default = new DefaultEditorFactory();
public GameObject CreateGameObject(string name, params Type[] components){ public GameObject CreateGameObject(string name, params Type[] components){
return ObjectFactory.CreateGameObject(name, components); return ObjectFactory.CreateGameObject(name, components);
} }
} }
#endregion #endregion
#endif #endif
} }
#endif #endif

View file

@ -5,105 +5,106 @@ using UnityEngine.UI;
using TMPro; using TMPro;
using UnityEngine.Audio; using UnityEngine.Audio;
[System.Serializable] public class OnPlay : UnityEngine.Events.UnityEvent { } namespace SimpleTools.Menu {
public class MenuController : MonoBehaviour{ [System.Serializable] public class OnPlay : UnityEngine.Events.UnityEvent { }
public class MenuController : MonoBehaviour {
[Header("Audio")] [Header("Audio")]
[SerializeField] AudioMixer mainMixer = default; [SerializeField] AudioMixer mainMixer = default;
[Tooltip("The music volume the first time you start the game")] [SerializeField, Range(0, 1)] float defaultMusicValue = .75f; [Tooltip("The music volume the first time you start the game")][SerializeField, Range(0, 1)] float defaultMusicValue = .75f;
[Tooltip("The SFX volume the first time you start the game")] [SerializeField, Range(0, 1)] float defaultSfxValue = .75f; [Tooltip("The SFX volume the first time you start the game")][SerializeField, Range(0, 1)] float defaultSfxValue = .75f;
public Slider musicSlider = default; public Slider musicSlider = default;
public Slider sfxSlider = default; public Slider sfxSlider = default;
[Header("Visual")] [Header("Visual")]
public TMP_Dropdown qualityDropdown = default; public TMP_Dropdown qualityDropdown = default;
int qualitySelected; int qualitySelected;
public TMP_Dropdown resolutionDropdown = default; public TMP_Dropdown resolutionDropdown = default;
Resolution[] resolutions; Resolution[] resolutions;
int currentResolutionIndex; int currentResolutionIndex;
[Space] [Space]
[SerializeField] OnPlay onPlay = default; [SerializeField] OnPlay onPlay = default;
void Awake(){ void Awake() {
if (mainMixer){ if (mainMixer) {
float musicVolume = PlayerPrefs.GetFloat("MusicVolume", defaultMusicValue); float musicVolume = PlayerPrefs.GetFloat("MusicVolume", defaultMusicValue);
float sfxVolume = PlayerPrefs.GetFloat("SFXVolume", defaultSfxValue); float sfxVolume = PlayerPrefs.GetFloat("SFXVolume", defaultSfxValue);
mainMixer.SetFloat("Master", Mathf.Log10(musicVolume <= .0001f ? .0001f : musicVolume) * 20); mainMixer.SetFloat("Master", Mathf.Log10(musicVolume <= .0001f ? .0001f : musicVolume) * 20);
mainMixer.SetFloat("SFX", Mathf.Log10(sfxVolume <= .0001f ? .0001f : sfxVolume) * 20); mainMixer.SetFloat("SFX", Mathf.Log10(sfxVolume <= .0001f ? .0001f : sfxVolume) * 20);
}
resolutions = Screen.resolutions.Select(resolution => new Resolution { width = resolution.width, height = resolution.height }).Distinct().ToArray();
resolutionDropdown.ClearOptions();
List<string> options = new List<string>();
for (int i = 0; i < resolutions.Length; i++){
string option = resolutions[i].width + "x" + resolutions[i].height;
options.Add(option);
if (resolutions[i].width == Screen.currentResolution.width && resolutions[i].height == Screen.currentResolution.height)
{
currentResolutionIndex = i;
} }
resolutions = Screen.resolutions.Select(resolution => new Resolution { width = resolution.width, height = resolution.height }).Distinct().ToArray();
resolutionDropdown.ClearOptions();
List<string> options = new List<string>();
for (int i = 0; i < resolutions.Length; i++) {
string option = resolutions[i].width + "x" + resolutions[i].height;
options.Add(option);
if (resolutions[i].width == Screen.currentResolution.width && resolutions[i].height == Screen.currentResolution.height) {
currentResolutionIndex = i;
}
}
resolutions.Reverse();
resolutionDropdown.AddOptions(options);
resolutionDropdown.value = currentResolutionIndex;
resolutionDropdown.RefreshShownValue();
qualityDropdown.ClearOptions();
List<string> qualityNames = new List<string>();
for (int i = 0; i < QualitySettings.names.Length; i++) {
qualityNames.Add(QualitySettings.names[i]);
}
qualityDropdown.AddOptions(qualityNames);
qualitySelected = PlayerPrefs.HasKey("QualitySelected") ? PlayerPrefs.GetInt("QualitySelected") : QualitySettings.GetQualityLevel();
qualityDropdown.value = qualitySelected;
QualitySettings.SetQualityLevel(qualitySelected);
qualityDropdown.RefreshShownValue();
} }
resolutions.Reverse(); void OnValidate() {
if (musicSlider) musicSlider.minValue = musicSlider.minValue < .0001f ? .0001f : musicSlider.minValue;
resolutionDropdown.AddOptions(options); if (sfxSlider) sfxSlider.minValue = sfxSlider.minValue < .0001f ? .0001f : sfxSlider.minValue;
resolutionDropdown.value = currentResolutionIndex;
resolutionDropdown.RefreshShownValue();
qualityDropdown.ClearOptions();
List<string> qualityNames = new List<string>();
for (int i = 0; i < QualitySettings.names.Length; i++){
qualityNames.Add(QualitySettings.names[i]);
} }
qualityDropdown.AddOptions(qualityNames);
qualitySelected = PlayerPrefs.HasKey("QualitySelected") ? PlayerPrefs.GetInt("QualitySelected") : QualitySettings.GetQualityLevel(); void Start() {
qualityDropdown.value = qualitySelected; musicSlider.value = PlayerPrefs.GetFloat("MusicVolume", defaultMusicValue);
QualitySettings.SetQualityLevel(qualitySelected); sfxSlider.value = PlayerPrefs.GetFloat("SFXVolume", defaultSfxValue);
qualityDropdown.RefreshShownValue(); }
}
void OnValidate(){ //Needs a slider between 0.0001 and 1
if (musicSlider) musicSlider.minValue = musicSlider.minValue < .0001f ? .0001f : musicSlider.minValue; public void SetMusicVolume(float sliderValue) {
if (sfxSlider) sfxSlider.minValue = sfxSlider.minValue < .0001f ? .0001f : sfxSlider.minValue; mainMixer.SetFloat("Master", Mathf.Log10(sliderValue) * 20);
} PlayerPrefs.SetFloat("MusicVolume", sliderValue);
}
void Start(){ //Needs a slider between 0.0001 and 1
musicSlider.value = PlayerPrefs.GetFloat("MusicVolume", defaultMusicValue); public void SetSfxVolume(float sliderValue) {
sfxSlider.value = PlayerPrefs.GetFloat("SFXVolume", defaultSfxValue); mainMixer.SetFloat("SFX", Mathf.Log10(sliderValue) * 20);
} PlayerPrefs.SetFloat("SFXVolume", sliderValue);
}
//Needs a slider between 0.0001 and 1 public void SetQuality(int qualityIndex) {
public void SetMusicVolume(float sliderValue){ QualitySettings.SetQualityLevel(qualityIndex);
mainMixer.SetFloat("Master", Mathf.Log10(sliderValue) * 20); PlayerPrefs.SetInt("QualitySelected", qualityIndex);
PlayerPrefs.SetFloat("MusicVolume", sliderValue); }
}
//Needs a slider between 0.0001 and 1 public void SetResolution(int resolutionIndex) {
public void SetSfxVolume(float sliderValue){ Resolution resolution = resolutions[resolutionIndex];
mainMixer.SetFloat("SFX", Mathf.Log10(sliderValue) * 20); Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreen);
PlayerPrefs.SetFloat("SFXVolume", sliderValue); }
}
public void SetQuality(int qualityIndex){ public void Play() {
QualitySettings.SetQualityLevel(qualityIndex); onPlay.Invoke();
PlayerPrefs.SetInt("QualitySelected", qualityIndex); }
}
public void SetResolution(int resolutionIndex){ public void Quit() {
Resolution resolution = resolutions[resolutionIndex]; Application.Quit();
Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreen); }
}
public void Play(){
onPlay.Invoke();
}
public void Quit(){
Application.Quit();
} }
} }

View file

@ -0,0 +1,12 @@
using UnityEngine;
namespace SimpleTools {
public static class MonobehaviourExtensions {
public static void EnsureCoroutineStopped(this MonoBehaviour value, ref Coroutine routine) {
if (routine != null) {
value.StopCoroutine(routine);
routine = null;
}
}
}
}

View file

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

View file

@ -1,3 +1,5 @@
public interface IPooledObject{ namespace SimpleTools.ObjectPooler {
void OnObjectSpawn(); public interface IPooledObject {
void OnObjectSpawn();
}
} }

View file

@ -1,18 +1,20 @@
using System.Collections.Generic; using System.Collections.Generic;
using UnityEngine; using UnityEngine;
[CreateAssetMenu(fileName = "New Pool", menuName = "Simple Tools/Pool", order = 11)] namespace SimpleTools.ObjectPooler {
public class Pool : ScriptableObject{ [CreateAssetMenu(fileName = "New Pool", menuName = "Simple Tools/Pool", order = 11)]
public class Pool : ScriptableObject {
public List<PoolPrefab> pools; public List<PoolPrefab> pools;
[System.Serializable] [System.Serializable]
public class PoolPrefab{ public class PoolPrefab {
public string tag; public string tag;
public GameObject prefab; public GameObject prefab;
public bool undetermined; public bool undetermined;
public int size; public int size;
[HideInInspector] public Queue<GameObject> determinedPool; [HideInInspector] public Queue<GameObject> determinedPool;
[HideInInspector] public List<GameObject> undeterminedPool; [HideInInspector] public List<GameObject> undeterminedPool;
}
} }
} }

View file

@ -2,368 +2,370 @@
using UnityEngine; using UnityEngine;
using UnityEngine.SceneManagement; using UnityEngine.SceneManagement;
public static class Pooler{ namespace SimpleTools.ObjectPooler {
public static class Pooler {
class PoolChecker : MonoBehaviour { class PoolChecker : MonoBehaviour {
public string poolTag; public string poolTag;
}
static Dictionary<string, Pool.PoolPrefab> poolDictionary;
static Scene poolScene;
/// <summary>Generate a scene with the objects of the pools in it
/// <para>If this isn't called, the pooler won't work</para>
/// </summary>
public static void CreatePools(Pool pool){
if(pool == null){
Debug.LogWarning("You have to provide a pool.");
return;
} }
poolDictionary = new Dictionary<string, Pool.PoolPrefab>(); static Dictionary<string, Pool.PoolPrefab> poolDictionary;
if (SceneManager.GetSceneByName("PoolScene").IsValid()){ static Scene poolScene;
poolScene = SceneManager.GetSceneByName("PoolScene");
}else{
poolScene = SceneManager.CreateScene("PoolScene");
}
foreach (Pool.PoolPrefab p in pool.pools){ /// <summary>Generate a scene with the objects of the pools in it
if (!p.undetermined){ /// <para>If this isn't called, the pooler won't work</para>
if(p.determinedPool == null){ /// </summary>
p.determinedPool = new Queue<GameObject>(); public static void CreatePools(Pool pool) {
} if (pool == null) {
for (int i = 0; i < p.size; i++){ Debug.LogWarning("You have to provide a pool.");
GameObject obj = Object.Instantiate(p.prefab); return;
obj.SetActive(false);
obj.AddComponent<PoolChecker>().poolTag = p.tag;
SceneManager.MoveGameObjectToScene(obj, poolScene);
p.determinedPool.Enqueue(obj);
}
}else{
if(p.undeterminedPool == null){
p.undeterminedPool = new List<GameObject>();
}
} }
poolDictionary.Add(p.tag, p);
}
}
/// <summary>Generate a scene with the objects of the pools in it
/// <para>If this isn't called, the pooler won't work</para>
/// </summary>
public static void CreatePools(Pool[] pools){
if (pools == null){
Debug.LogWarning("You have to provide a pool.");
return;
}
poolDictionary = new Dictionary<string, Pool.PoolPrefab>(); poolDictionary = new Dictionary<string, Pool.PoolPrefab>();
if (SceneManager.GetSceneByName("PoolScene").IsValid()){ if (SceneManager.GetSceneByName("PoolScene").IsValid()) {
poolScene = SceneManager.GetSceneByName("PoolScene"); poolScene = SceneManager.GetSceneByName("PoolScene");
}else{ } else {
poolScene = SceneManager.CreateScene("PoolScene"); poolScene = SceneManager.CreateScene("PoolScene");
} }
for (int i = 0; i < pools.Length; i++){ foreach (Pool.PoolPrefab p in pool.pools) {
foreach (Pool.PoolPrefab p in pools[i].pools){ if (!p.undetermined) {
if (!p.undetermined){ if (p.determinedPool == null) {
if (p.determinedPool == null){
p.determinedPool = new Queue<GameObject>(); p.determinedPool = new Queue<GameObject>();
} }
for (int j = 0; j < p.size; j++){ for (int i = 0; i < p.size; i++) {
GameObject obj = Object.Instantiate(p.prefab); GameObject obj = Object.Instantiate(p.prefab);
obj.SetActive(false); obj.SetActive(false);
obj.AddComponent<PoolChecker>().poolTag = p.tag; obj.AddComponent<PoolChecker>().poolTag = p.tag;
SceneManager.MoveGameObjectToScene(obj, poolScene); SceneManager.MoveGameObjectToScene(obj, poolScene);
p.determinedPool.Enqueue(obj); p.determinedPool.Enqueue(obj);
} }
}else{ } else {
if (p.undeterminedPool == null){ if (p.undeterminedPool == null) {
p.undeterminedPool = new List<GameObject>(); p.undeterminedPool = new List<GameObject>();
} }
} }
poolDictionary.Add(p.tag, p); poolDictionary.Add(p.tag, p);
} }
} }
} /// <summary>Generate a scene with the objects of the pools in it
/// <summary>Destroy an object and return it to the pool scene /// <para>If this isn't called, the pooler won't work</para>
/// </summary> /// </summary>
public static void Destroy(GameObject gameObject){ public static void CreatePools(Pool[] pools) {
PoolChecker poolChecker = gameObject.GetComponent<PoolChecker>(); if (pools == null) {
if (poolChecker == null){ Debug.LogWarning("You have to provide a pool.");
Debug.LogWarning("GameObject: " + gameObject + " isn't from a pool", gameObject); return;
return; }
}
gameObject.transform.SetParent(null); poolDictionary = new Dictionary<string, Pool.PoolPrefab>();
SceneManager.MoveGameObjectToScene(gameObject, poolScene); if (SceneManager.GetSceneByName("PoolScene").IsValid()) {
poolScene = SceneManager.GetSceneByName("PoolScene");
} else {
poolScene = SceneManager.CreateScene("PoolScene");
}
if (poolDictionary.ContainsKey(poolChecker.poolTag)){ for (int i = 0; i < pools.Length; i++) {
Pool.PoolPrefab pool = poolDictionary[poolChecker.poolTag]; foreach (Pool.PoolPrefab p in pools[i].pools) {
if (pool.undetermined){ if (!p.undetermined) {
gameObject.SetActive(false); if (p.determinedPool == null) {
pool.undeterminedPool.Remove(gameObject); p.determinedPool = new Queue<GameObject>();
}else{ }
gameObject.SetActive(false); for (int j = 0; j < p.size; j++) {
GameObject obj = Object.Instantiate(p.prefab);
obj.SetActive(false);
obj.AddComponent<PoolChecker>().poolTag = p.tag;
SceneManager.MoveGameObjectToScene(obj, poolScene);
p.determinedPool.Enqueue(obj);
}
} else {
if (p.undeterminedPool == null) {
p.undeterminedPool = new List<GameObject>();
}
}
poolDictionary.Add(p.tag, p);
}
} }
} }
} /// <summary>Destroy an object and return it to the pool scene
/// </summary>
public static void Destroy(GameObject gameObject) {
PoolChecker poolChecker = gameObject.GetComponent<PoolChecker>();
if (poolChecker == null) {
Debug.LogWarning("GameObject: " + gameObject + " isn't from a pool", gameObject);
return;
}
/// <summary>Spawn an object into a specific position gameObject.transform.SetParent(null);
/// <para>The CreatePools function must have been called before.</para> SceneManager.MoveGameObjectToScene(gameObject, poolScene);
/// </summary>
public static GameObject SpawnFromPool(string tag, Vector3 position){ if (poolDictionary.ContainsKey(poolChecker.poolTag)) {
if (!poolDictionary.ContainsKey(tag)){ Pool.PoolPrefab pool = poolDictionary[poolChecker.poolTag];
Debug.Log("Pool with tag " + tag + " doesn't exist."); if (pool.undetermined) {
return null; gameObject.SetActive(false);
pool.undeterminedPool.Remove(gameObject);
} else {
gameObject.SetActive(false);
}
}
} }
Pool.PoolPrefab pool = poolDictionary[tag]; /// <summary>Spawn an object into a specific position
GameObject objectToSpawn; /// <para>The CreatePools function must have been called before.</para>
if (!pool.undetermined){ /// </summary>
objectToSpawn = pool.determinedPool.Dequeue(); public static GameObject SpawnFromPool(string tag, Vector3 position) {
if (!poolDictionary.ContainsKey(tag)) {
Debug.Log("Pool with tag " + tag + " doesn't exist.");
return null;
}
objectToSpawn.transform.position = position; Pool.PoolPrefab pool = poolDictionary[tag];
objectToSpawn.transform.rotation = Quaternion.identity; GameObject objectToSpawn;
objectToSpawn.SetActive(true); if (!pool.undetermined) {
objectToSpawn = pool.determinedPool.Dequeue();
pool.determinedPool.Enqueue(objectToSpawn);
}else{
if(pool.undeterminedPool.Count != 0){
int lastIndex = pool.undeterminedPool.Count - 1;
objectToSpawn = pool.undeterminedPool[lastIndex];
objectToSpawn.transform.position = position; objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = Quaternion.identity; objectToSpawn.transform.rotation = Quaternion.identity;
objectToSpawn.SetActive(true); objectToSpawn.SetActive(true);
}else{
objectToSpawn = Object.Instantiate(pool.prefab, position, Quaternion.identity); pool.determinedPool.Enqueue(objectToSpawn);
SceneManager.MoveGameObjectToScene(objectToSpawn, poolScene); } else {
objectToSpawn.AddComponent<PoolChecker>().poolTag = tag; if (pool.undeterminedPool.Count != 0) {
int lastIndex = pool.undeterminedPool.Count - 1;
objectToSpawn = pool.undeterminedPool[lastIndex];
objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = Quaternion.identity;
objectToSpawn.SetActive(true);
} else {
objectToSpawn = Object.Instantiate(pool.prefab, position, Quaternion.identity);
SceneManager.MoveGameObjectToScene(objectToSpawn, poolScene);
objectToSpawn.AddComponent<PoolChecker>().poolTag = tag;
}
} }
IPooledObject pooledObj = objectToSpawn.GetComponent<IPooledObject>();
if (pooledObj != null) {
pooledObj.OnObjectSpawn();
}
return objectToSpawn;
} }
/// <summary>Spawn an object into a specific position and parent
/// <para>The CreatePools function must have been called before.</para>
/// </summary>
public static GameObject SpawnFromPool(string tag, Vector3 position, Transform parent) {
if (!poolDictionary.ContainsKey(tag)) {
Debug.Log("Pool with tag " + tag + " doesn't exist.");
return null;
}
IPooledObject pooledObj = objectToSpawn.GetComponent<IPooledObject>(); Pool.PoolPrefab pool = poolDictionary[tag];
if(pooledObj != null){ GameObject objectToSpawn;
pooledObj.OnObjectSpawn(); if (!pool.undetermined) {
} objectToSpawn = pool.determinedPool.Dequeue();
return objectToSpawn;
}
/// <summary>Spawn an object into a specific position and parent
/// <para>The CreatePools function must have been called before.</para>
/// </summary>
public static GameObject SpawnFromPool(string tag, Vector3 position, Transform parent){
if (!poolDictionary.ContainsKey(tag)){
Debug.Log("Pool with tag " + tag + " doesn't exist.");
return null;
}
Pool.PoolPrefab pool = poolDictionary[tag];
GameObject objectToSpawn;
if (!pool.undetermined){
objectToSpawn = pool.determinedPool.Dequeue();
objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = Quaternion.identity;
objectToSpawn.transform.SetParent(parent);
objectToSpawn.SetActive(true);
pool.determinedPool.Enqueue(objectToSpawn);
}else{
if (pool.undeterminedPool.Count != 0){
int lastIndex = pool.undeterminedPool.Count - 1;
objectToSpawn = pool.undeterminedPool[lastIndex];
objectToSpawn.transform.position = position; objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = Quaternion.identity; objectToSpawn.transform.rotation = Quaternion.identity;
objectToSpawn.transform.SetParent(parent); objectToSpawn.transform.SetParent(parent);
objectToSpawn.SetActive(true); objectToSpawn.SetActive(true);
}else{
objectToSpawn = Object.Instantiate(pool.prefab, position, Quaternion.identity, parent); pool.determinedPool.Enqueue(objectToSpawn);
objectToSpawn.AddComponent<PoolChecker>().poolTag = tag; } else {
if (pool.undeterminedPool.Count != 0) {
int lastIndex = pool.undeterminedPool.Count - 1;
objectToSpawn = pool.undeterminedPool[lastIndex];
objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = Quaternion.identity;
objectToSpawn.transform.SetParent(parent);
objectToSpawn.SetActive(true);
} else {
objectToSpawn = Object.Instantiate(pool.prefab, position, Quaternion.identity, parent);
objectToSpawn.AddComponent<PoolChecker>().poolTag = tag;
}
} }
IPooledObject pooledObj = objectToSpawn.GetComponent<IPooledObject>();
if (pooledObj != null) {
pooledObj.OnObjectSpawn();
}
return objectToSpawn;
} }
/// <summary>Spawn an object into a specific position, parent and set if it's in world space or not
/// <para>The CreatePools function must have been called before.</para>
/// </summary>
public static GameObject SpawnFromPool(string tag, Vector3 position, Transform parent, bool instantiateInWorldSpace) {
if (!poolDictionary.ContainsKey(tag)) {
Debug.Log("Pool with tag " + tag + " doesn't exist.");
return null;
}
IPooledObject pooledObj = objectToSpawn.GetComponent<IPooledObject>(); if (!instantiateInWorldSpace) {
if (pooledObj != null){ SpawnFromPool(tag, position, parent);
pooledObj.OnObjectSpawn(); }
}
return objectToSpawn;
}
/// <summary>Spawn an object into a specific position, parent and set if it's in world space or not
/// <para>The CreatePools function must have been called before.</para>
/// </summary>
public static GameObject SpawnFromPool(string tag, Vector3 position, Transform parent, bool instantiateInWorldSpace){
if (!poolDictionary.ContainsKey(tag)){
Debug.Log("Pool with tag " + tag + " doesn't exist.");
return null;
}
if (!instantiateInWorldSpace){ Pool.PoolPrefab pool = poolDictionary[tag];
SpawnFromPool(tag, position, parent); GameObject objectToSpawn;
} if (!pool.undetermined) {
objectToSpawn = pool.determinedPool.Dequeue();
Pool.PoolPrefab pool = poolDictionary[tag];
GameObject objectToSpawn;
if (!pool.undetermined){
objectToSpawn = pool.determinedPool.Dequeue();
objectToSpawn.transform.localPosition = position;
objectToSpawn.transform.localRotation = Quaternion.identity;
objectToSpawn.transform.SetParent(parent);
objectToSpawn.SetActive(true);
pool.determinedPool.Enqueue(objectToSpawn);
}else{
if (pool.undeterminedPool.Count != 0){
int lastIndex = pool.undeterminedPool.Count - 1;
objectToSpawn = pool.undeterminedPool[lastIndex];
objectToSpawn.transform.localPosition = position; objectToSpawn.transform.localPosition = position;
objectToSpawn.transform.localRotation = Quaternion.identity; objectToSpawn.transform.localRotation = Quaternion.identity;
objectToSpawn.transform.SetParent(parent); objectToSpawn.transform.SetParent(parent);
objectToSpawn.SetActive(true); objectToSpawn.SetActive(true);
}else{
objectToSpawn = Object.Instantiate(pool.prefab); pool.determinedPool.Enqueue(objectToSpawn);
objectToSpawn.transform.localPosition = position; } else {
objectToSpawn.transform.localRotation = Quaternion.identity; if (pool.undeterminedPool.Count != 0) {
objectToSpawn.transform.SetParent(parent); int lastIndex = pool.undeterminedPool.Count - 1;
objectToSpawn.AddComponent<PoolChecker>().poolTag = tag; objectToSpawn = pool.undeterminedPool[lastIndex];
objectToSpawn.transform.localPosition = position;
objectToSpawn.transform.localRotation = Quaternion.identity;
objectToSpawn.transform.SetParent(parent);
objectToSpawn.SetActive(true);
} else {
objectToSpawn = Object.Instantiate(pool.prefab);
objectToSpawn.transform.localPosition = position;
objectToSpawn.transform.localRotation = Quaternion.identity;
objectToSpawn.transform.SetParent(parent);
objectToSpawn.AddComponent<PoolChecker>().poolTag = tag;
}
} }
IPooledObject pooledObj = objectToSpawn.GetComponent<IPooledObject>();
if (pooledObj != null) {
pooledObj.OnObjectSpawn();
}
return objectToSpawn;
} }
/// <summary>Spawn an object into a specific position and rotation
/// <para>The CreatePools function must have been called before.</para>
/// </summary>
public static GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation) {
if (!poolDictionary.ContainsKey(tag)) {
Debug.Log("Pool with tag " + tag + " doesn't exist.");
return null;
}
IPooledObject pooledObj = objectToSpawn.GetComponent<IPooledObject>(); Pool.PoolPrefab pool = poolDictionary[tag];
if (pooledObj != null){ GameObject objectToSpawn;
pooledObj.OnObjectSpawn(); if (!pool.undetermined) {
} objectToSpawn = pool.determinedPool.Dequeue();
return objectToSpawn;
}
/// <summary>Spawn an object into a specific position and rotation
/// <para>The CreatePools function must have been called before.</para>
/// </summary>
public static GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation){
if (!poolDictionary.ContainsKey(tag)){
Debug.Log("Pool with tag " + tag + " doesn't exist.");
return null;
}
Pool.PoolPrefab pool = poolDictionary[tag];
GameObject objectToSpawn;
if (!pool.undetermined){
objectToSpawn = pool.determinedPool.Dequeue();
objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = rotation;
objectToSpawn.SetActive(true);
pool.determinedPool.Enqueue(objectToSpawn);
}else{
if (pool.undeterminedPool.Count != 0){
int lastIndex = pool.undeterminedPool.Count - 1;
objectToSpawn = pool.undeterminedPool[lastIndex];
objectToSpawn.transform.position = position; objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = rotation; objectToSpawn.transform.rotation = rotation;
objectToSpawn.SetActive(true); objectToSpawn.SetActive(true);
}else{
objectToSpawn = Object.Instantiate(pool.prefab, position, rotation); pool.determinedPool.Enqueue(objectToSpawn);
SceneManager.MoveGameObjectToScene(objectToSpawn, poolScene); } else {
objectToSpawn.AddComponent<PoolChecker>().poolTag = tag; if (pool.undeterminedPool.Count != 0) {
int lastIndex = pool.undeterminedPool.Count - 1;
objectToSpawn = pool.undeterminedPool[lastIndex];
objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = rotation;
objectToSpawn.SetActive(true);
} else {
objectToSpawn = Object.Instantiate(pool.prefab, position, rotation);
SceneManager.MoveGameObjectToScene(objectToSpawn, poolScene);
objectToSpawn.AddComponent<PoolChecker>().poolTag = tag;
}
} }
IPooledObject pooledObj = objectToSpawn.GetComponent<IPooledObject>();
if (pooledObj != null) {
pooledObj.OnObjectSpawn();
}
return objectToSpawn;
} }
/// <summary>Spawn an object into a specific position, rotation and parent
/// <para>The CreatePools function must have been called before.</para>
/// </summary>
public static GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation, Transform parent) {
if (!poolDictionary.ContainsKey(tag)) {
Debug.Log("Pool with tag " + tag + " doesn't exist.");
return null;
}
IPooledObject pooledObj = objectToSpawn.GetComponent<IPooledObject>(); Pool.PoolPrefab pool = poolDictionary[tag];
if (pooledObj != null){ GameObject objectToSpawn;
pooledObj.OnObjectSpawn(); if (!pool.undetermined) {
} objectToSpawn = pool.determinedPool.Dequeue();
return objectToSpawn;
}
/// <summary>Spawn an object into a specific position, rotation and parent
/// <para>The CreatePools function must have been called before.</para>
/// </summary>
public static GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation, Transform parent){
if (!poolDictionary.ContainsKey(tag)){
Debug.Log("Pool with tag " + tag + " doesn't exist.");
return null;
}
Pool.PoolPrefab pool = poolDictionary[tag];
GameObject objectToSpawn;
if (!pool.undetermined){
objectToSpawn = pool.determinedPool.Dequeue();
objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = rotation;
objectToSpawn.transform.SetParent(parent);
objectToSpawn.SetActive(true);
pool.determinedPool.Enqueue(objectToSpawn);
}else{
if (pool.undeterminedPool.Count != 0){
int lastIndex = pool.undeterminedPool.Count - 1;
objectToSpawn = pool.undeterminedPool[lastIndex];
objectToSpawn.transform.position = position; objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = rotation; objectToSpawn.transform.rotation = rotation;
objectToSpawn.transform.SetParent(parent); objectToSpawn.transform.SetParent(parent);
objectToSpawn.SetActive(true); objectToSpawn.SetActive(true);
}else{
objectToSpawn = Object.Instantiate(pool.prefab, position, rotation, parent); pool.determinedPool.Enqueue(objectToSpawn);
objectToSpawn.AddComponent<PoolChecker>().poolTag = tag; } else {
if (pool.undeterminedPool.Count != 0) {
int lastIndex = pool.undeterminedPool.Count - 1;
objectToSpawn = pool.undeterminedPool[lastIndex];
objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = rotation;
objectToSpawn.transform.SetParent(parent);
objectToSpawn.SetActive(true);
} else {
objectToSpawn = Object.Instantiate(pool.prefab, position, rotation, parent);
objectToSpawn.AddComponent<PoolChecker>().poolTag = tag;
}
} }
IPooledObject pooledObj = objectToSpawn.GetComponent<IPooledObject>();
if (pooledObj != null) {
pooledObj.OnObjectSpawn();
}
return objectToSpawn;
} }
/// <summary>Spawn an object into a specific position, rotation, parent and set if it's in world space or not
/// <para>The CreatePools function must have been called before.</para>
/// </summary>
public static GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation, Transform parent, bool instantiateInWorldSpace) {
if (!poolDictionary.ContainsKey(tag)) {
Debug.Log("Pool with tag " + tag + " doesn't exist.");
return null;
}
IPooledObject pooledObj = objectToSpawn.GetComponent<IPooledObject>(); if (!instantiateInWorldSpace) {
if (pooledObj != null){ SpawnFromPool(tag, position, rotation, parent);
pooledObj.OnObjectSpawn(); }
}
return objectToSpawn;
}
/// <summary>Spawn an object into a specific position, rotation, parent and set if it's in world space or not
/// <para>The CreatePools function must have been called before.</para>
/// </summary>
public static GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation, Transform parent, bool instantiateInWorldSpace){
if (!poolDictionary.ContainsKey(tag)){
Debug.Log("Pool with tag " + tag + " doesn't exist.");
return null;
}
if (!instantiateInWorldSpace){ Pool.PoolPrefab pool = poolDictionary[tag];
SpawnFromPool(tag, position, rotation, parent); GameObject objectToSpawn;
} if (!pool.undetermined) {
objectToSpawn = pool.determinedPool.Dequeue();
Pool.PoolPrefab pool = poolDictionary[tag];
GameObject objectToSpawn;
if (!pool.undetermined){
objectToSpawn = pool.determinedPool.Dequeue();
objectToSpawn.transform.localPosition = position;
objectToSpawn.transform.localRotation = rotation;
objectToSpawn.transform.SetParent(parent);
objectToSpawn.SetActive(true);
pool.determinedPool.Enqueue(objectToSpawn);
}else{
if (pool.undeterminedPool.Count != 0){
int lastIndex = pool.undeterminedPool.Count - 1;
objectToSpawn = pool.undeterminedPool[lastIndex];
objectToSpawn.transform.localPosition = position; objectToSpawn.transform.localPosition = position;
objectToSpawn.transform.localRotation = rotation; objectToSpawn.transform.localRotation = rotation;
objectToSpawn.transform.SetParent(parent); objectToSpawn.transform.SetParent(parent);
objectToSpawn.SetActive(true); objectToSpawn.SetActive(true);
}else{
objectToSpawn = Object.Instantiate(pool.prefab);
objectToSpawn.transform.localPosition = position;
objectToSpawn.transform.localRotation = rotation;
objectToSpawn.transform.SetParent(parent);
objectToSpawn.AddComponent<PoolChecker>().poolTag = tag;
}
}
IPooledObject pooledObj = objectToSpawn.GetComponent<IPooledObject>(); pool.determinedPool.Enqueue(objectToSpawn);
if (pooledObj != null){ } else {
pooledObj.OnObjectSpawn(); if (pool.undeterminedPool.Count != 0) {
int lastIndex = pool.undeterminedPool.Count - 1;
objectToSpawn = pool.undeterminedPool[lastIndex];
objectToSpawn.transform.localPosition = position;
objectToSpawn.transform.localRotation = rotation;
objectToSpawn.transform.SetParent(parent);
objectToSpawn.SetActive(true);
} else {
objectToSpawn = Object.Instantiate(pool.prefab);
objectToSpawn.transform.localPosition = position;
objectToSpawn.transform.localRotation = rotation;
objectToSpawn.transform.SetParent(parent);
objectToSpawn.AddComponent<PoolChecker>().poolTag = tag;
}
}
IPooledObject pooledObj = objectToSpawn.GetComponent<IPooledObject>();
if (pooledObj != null) {
pooledObj.OnObjectSpawn();
}
return objectToSpawn;
} }
return objectToSpawn;
} }
} }

View file

@ -3,67 +3,69 @@ using System.Collections;
using UnityEngine; using UnityEngine;
using UnityEngine.SceneManagement; using UnityEngine.SceneManagement;
public static class Loader{ namespace SimpleTools.SceneManagement {
public static class Loader {
class LoadingMonoBehaviour : MonoBehaviour { } class LoadingMonoBehaviour : MonoBehaviour { }
static Action onLoaderCallback; static Action onLoaderCallback;
static AsyncOperation loadingAsyncOperation; static AsyncOperation loadingAsyncOperation;
/// <summary>Load a scene with a loading scene /// <summary>Load a scene with a loading scene
/// <para>It requires a scene called "Loading" where the loading screen is located.</para> /// <para>It requires a scene called "Loading" where the loading screen is located.</para>
/// </summary> /// </summary>
public static void Load(int scene){ public static void Load(int scene) {
onLoaderCallback = () => { onLoaderCallback = () => {
GameObject loadingGameObject = new GameObject("LoadingGameObject"); GameObject loadingGameObject = new GameObject("LoadingGameObject");
loadingGameObject.AddComponent<LoadingMonoBehaviour>().StartCoroutine(LoadSceneAsync(scene)); loadingGameObject.AddComponent<LoadingMonoBehaviour>().StartCoroutine(LoadSceneAsync(scene));
}; };
SceneManager.LoadScene("Loading"); SceneManager.LoadScene("Loading");
} }
/// <summary>Load a scene with a loading scene /// <summary>Load a scene with a loading scene
/// <para>It requires a scene called "Loading" where the loading screen is located.</para> /// <para>It requires a scene called "Loading" where the loading screen is located.</para>
/// </summary> /// </summary>
public static void Load(string scene){ public static void Load(string scene) {
onLoaderCallback = () => { onLoaderCallback = () => {
GameObject loadingGameObject = new GameObject("LoadingGameObject"); GameObject loadingGameObject = new GameObject("LoadingGameObject");
loadingGameObject.AddComponent<LoadingMonoBehaviour>().StartCoroutine(LoadSceneAsync(scene)); loadingGameObject.AddComponent<LoadingMonoBehaviour>().StartCoroutine(LoadSceneAsync(scene));
}; };
SceneManager.LoadScene("Loading"); SceneManager.LoadScene("Loading");
} }
static IEnumerator LoadSceneAsync(int scene){ static IEnumerator LoadSceneAsync(int scene) {
yield return null;
loadingAsyncOperation = SceneManager.LoadSceneAsync(scene);
while (!loadingAsyncOperation.isDone){
yield return null; yield return null;
} loadingAsyncOperation = SceneManager.LoadSceneAsync(scene);
}
static IEnumerator LoadSceneAsync(string scene){
yield return null;
loadingAsyncOperation = SceneManager.LoadSceneAsync(scene);
while (!loadingAsyncOperation.isDone){ while (!loadingAsyncOperation.isDone) {
yield return null;
}
}
static IEnumerator LoadSceneAsync(string scene) {
yield return null; yield return null;
} loadingAsyncOperation = SceneManager.LoadSceneAsync(scene);
}
/// <summary>Returns the loading progress while (!loadingAsyncOperation.isDone) {
/// </summary> yield return null;
public static float GetLoadingProgress(){ }
if(loadingAsyncOperation != null){
return loadingAsyncOperation.progress;
}else{
return 0f;
} }
}
public static void LoaderCallback(){ /// <summary>Returns the loading progress
if(onLoaderCallback != null){ /// </summary>
onLoaderCallback(); public static float GetLoadingProgress() {
onLoaderCallback = null; if (loadingAsyncOperation != null) {
return loadingAsyncOperation.progress;
} else {
return 0f;
}
}
public static void LoaderCallback() {
if (onLoaderCallback != null) {
onLoaderCallback();
onLoaderCallback = null;
}
} }
} }
} }

View file

@ -1,14 +1,16 @@
using UnityEngine; using UnityEngine;
public class LoaderCallback : MonoBehaviour{ namespace SimpleTools.SceneManagement {
public class LoaderCallback : MonoBehaviour {
bool isFirstUpdate = true; bool isFirstUpdate = true;
// Update is called once per frame // Update is called once per frame
void Update(){ void Update() {
if (isFirstUpdate){ if (isFirstUpdate) {
isFirstUpdate = false; isFirstUpdate = false;
Loader.LoaderCallback(); Loader.LoaderCallback();
}
} }
} }
} }

View file

@ -1,17 +1,19 @@
using UnityEngine; using UnityEngine;
using UnityEngine.UI; using UnityEngine.UI;
public class LoadingProgressBar : MonoBehaviour{ namespace SimpleTools.SceneManagement {
public class LoadingProgressBar : MonoBehaviour {
Image image; Image image;
// Start is called before the first frame update // Start is called before the first frame update
void Awake(){ void Awake() {
image = transform.GetComponent<Image>(); image = transform.GetComponent<Image>();
} }
// Update is called once per frame // Update is called once per frame
void Update(){ void Update() {
image.fillAmount = Loader.GetLoadingProgress(); image.fillAmount = Loader.GetLoadingProgress();
}
} }
} }

View file

@ -75,7 +75,7 @@ namespace SimpleTools.Timer{
} }
/// <summary> /// <summary>
/// Pause and sets the time to the default one /// Pause and sets the time to the defaultOne
/// </summary> /// </summary>
public void ResetTimer(){ public void ResetTimer(){
isPaused = true; isPaused = true;

View file

@ -5,32 +5,32 @@ using System;
using TMPro; using TMPro;
namespace SimpleTools.Timer{ namespace SimpleTools.Timer{
public static class TimerUtility { public static class TimerUtility {
/// <summary> /// <summary>
/// Setup the timer /// Setup the timer
/// </summary> /// </summary>
/// <param name="container">TMPro object that will contain the timer</param> /// <param name="container">TMPro object that will contain the timer</param>
/// <param name="timerType">What type of timer will it be (Countdown, Stopwatch, Clock)</param> /// <param name="timerType">What type of timer will it be (Countdown, Stopwatch, Clock)</param>
/// <param name="countdownTime">The time that will have in case it is a countdown timer</param> /// <param name="countdownTime">The time that will have in case it is a countdown timer</param>
/// <returns></returns> /// <returns></returns>
public static Timer SetupTimer(this TMP_Text container, TimerType timerType, TimerUpdate timerUpdate, float countdownTime = 60f){ public static Timer SetupTimer(this TMP_Text container, TimerType timerType, TimerUpdate timerUpdate, float countdownTime = 60f){
Timer t = container.gameObject.AddComponent<Timer>(); Timer t = container.gameObject.AddComponent<Timer>();
float elapsedTime = 0f; float elapsedTime = 0f;
string text = string.Empty; string text = string.Empty;
TimeSpan timePlaying = TimeSpan.Zero; TimeSpan timePlaying = TimeSpan.Zero;
switch (timerType){ switch (timerType){
case TimerType.Countdown: case TimerType.Countdown:
elapsedTime = countdownTime; elapsedTime = countdownTime;
timePlaying = TimeSpan.FromSeconds(elapsedTime); timePlaying = TimeSpan.FromSeconds(elapsedTime);
text = timePlaying.ToString("m':'ss'.'ff"); text = timePlaying.ToString("m':'ss'.'ff");
break; break;
case TimerType.Clock: case TimerType.Clock:
text = DateTime.Now.ToString("HH:mm:ss"); text = DateTime.Now.ToString("HH:mm:ss");
break; break;
} }
t.Setup(elapsedTime, true, timePlaying, container, timerType, timerUpdate, text); t.Setup(elapsedTime, true, timePlaying, container, timerType, timerUpdate, text);
return t; return t;
} }
} }
} }

View file

@ -1,6 +1,6 @@
{ {
"name": "com.geri.simpletools", "name": "com.geri.simpletools",
"version": "1.1.2", "version": "1.2.0",
"displayName": "Simple Tools", "displayName": "Simple Tools",
"description": "This package contains simple tools to use in your project.", "description": "This package contains simple tools to use in your project.",
"unity": "2018.4", "unity": "2018.4",