Skip to content

Instantly share code, notes, and snippets.

@blackbret94
Created June 8, 2019 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blackbret94/7da50352537fa4a9d7381f9287a70027 to your computer and use it in GitHub Desktop.
Save blackbret94/7da50352537fa4a9d7381f9287a70027 to your computer and use it in GitHub Desktop.
A useful model for creating ScriptableObject directories in Unity. This makes it easy to create an asset that stores AudioClips, Sprites, and other sets of data you want to be able to reference in many places throughout your project. Can be accessed like a Dictionary[string]. I use many variations of this in all my Unity projects.
using System.Collections.Generic;
using UnityEngine;
namespace Util.Directories
{
[CreateAssetMenu(fileName = "AudioDirectory", menuName = "Directory/Audio Directory", order = 1)]
public class AudioDirectory : ScriptableObject
{
public Wrapper[] Directory;
private Dictionary<string, AudioClip> _dictionary;
void OnEnable()
{
CreateDictionaryIfDoesNotExist();
}
private void CreateDictionaryIfDoesNotExist()
{
if (_dictionary != null)
return;
_dictionary = new Dictionary<string, AudioClip>();
foreach (Wrapper acw in Directory)
_dictionary.Add(acw.Name,acw.AudioClip);
}
/// <summary>
/// Use this accessor to get the desired clip from other classes
/// audioDirectory["shoot"]
/// </summary>
/// <param name="key"></param>
public AudioClip this[string key] => _dictionary.ContainsKey(key) ? _dictionary[key] : null;
/// <summary>
/// This wrapper allows you to specify audioclips from the inspector. System.Collections.Generic Dictionary is not
/// serializable.
/// </summary>
[System.Serializable]
public struct Wrapper
{
public string Name;
public AudioClip AudioClip;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment