How to execute a function in editor to populate an array?

I want to create an List with all my audios so it can then be used as some kind of database of audio files to be played in the game.


Those audio clips are in a resource folder Resources/Audio/GameAudio/DirectorSentences


I want to populate my List automatically by reading the content of the folder and loading all the file in edit mode. So when I add new Audio Clips in my folder it updates my AudioClip List


Here is what I did:

public class DirectorInterventions : MonoBehaviour
{
    public List<SoundAudioClip> DirectorAudio;
    public string FolderName;

    private void Awake()
    {
        GenerateSound(FolderName);
    }

    private void GenerateSound(string path)
    {
        string directory = "GameAudio/" + path;
        foreach (AudioClip audioClip in Resources.LoadAll<AudioClip>(path))
        {
            Debug.Log(audioClip.name);
            // adding audio files in my SoundAudioClip list
        }
        
    }
    
    [System.Serializable]
    public class SoundAudioClip
    {
        public string sound;
        public AudioClip audioClip;
        
        public SoundAudioClip(AudioClip clip)
        {
            this.sound = clip.name;
            this.audioClip = clip;
        }
    }
}

But I still don’t understand How to make GenerateSound() execute in editor, without having to play the game.


Can you help me ?


Thank you in advance

You can add a [ContextMenu] attribute to a function, this will make it appear in the right click menu for that component:

https://pixelpirate.github.io/UnityEditorExtentionsBook/component-context-menu.html

As andrew-lukasik said, OnValidate works too and will happen automatically but since when entering or exiting play mode and when any fields are changed on that component then it could be quite a heavy operation to happen so frequently. I worked on a large project where we overused OnValidate and it slowed the editor right down.

Up to you which of these two options you think best suits your project. :slight_smile: