Snippets

Sam Gates Otto - Populate your public variables with a single click!

You are viewing an old version of this snippet. View the current version.
Revised by Sam Gates 5b52358
using System;
using UnityEngine;
using UnityEditor;

//Add to an Editor folder
public class Otto
{
    /// <summary>
    /// Loops through all public fields on the target mono behaviour and searches for a relevant asset in the asset database
    /// Separate your search terms with an underscore, and being as specific as possible with your variable names helps Otto to find the right assets
    /// Example: "Optimistic Unicorn.mp4" can be found with variable names "Optimistic", "Unicorn", or best of all: "Optimistic_Unicorn"
    /// </summary>
    [MenuItem("CONTEXT/MonoBehaviour/Auto Populate Variables")]
    static void AutoPopulate(MenuCommand command)
    {
        Debug.Log("[Otto]: Auto populating variables");
        var type = command.context.GetType();
        Debug.Log($"[Otto]: Doing a kickflip over the {type.Name}");
        var fields = type.GetFields();
        var fieldsSet = 0;
        for (int i = 0; i < fields.Length; i++)
        {
            var assetName = fields[i].Name.Split('_');
            var asset = AssetDatabase.FindAssets(String.Join(" ",assetName));
            if (asset.Length > 0)
            {
                var assetPath = AssetDatabase.GUIDToAssetPath(asset[0]);
                var loadedAsset = AssetDatabase.LoadAssetAtPath(assetPath, fields[i].FieldType);
                if (loadedAsset != null)
                {
                    Undo.RecordObject(command.context,$"Set field {fields[i].Name}");
                    fieldsSet++;
                    fields[i].SetValue(command.context, loadedAsset);
                }
            }
        }
        Debug.Log($"[Otto]: All done! I set {fieldsSet} fields");
    }
}
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.