Example-Code / Editor Scripts / AddNameSpace.cs
AddNameSpace.cs
Raw
using System;
using System.Globalization;
using System.IO;
using UnityEditor;
namespace CCG.Bigfoot.Editor
{
    /// <summary>
    /// Provides an automatic namespace to newly created C# scripts based on folder structure.
    /// </summary> 
    /// <remarks>
    /// Authors: CS
    /// Created: 2023-12-28
    /// </remarks>
    public sealed class AddNameSpace : UnityEditor.AssetModificationProcessor
    {
        public static void OnWillCreateAsset(string path)
        {
            if (!path.EndsWith(".cs.meta")) return;

            string originalFilePath = AssetDatabase.GetAssetPathFromTextMetaFilePath(path);

            try
            {
                ProcessScriptFile(originalFilePath);
            }
            catch
            {
                UnityEngine.Debug.LogError($"[OnWillCreateAsset] - Error processing script!");
            }
        }

        private static void ProcessScriptFile(string filePath)
        {
            string fileContent = File.ReadAllText(filePath);
            int indexOfStartOfFileName = filePath.LastIndexOf('/');

            if (indexOfStartOfFileName == -1)
            {
                UnityEngine.Debug.LogError("[ProcessScriptFile] - Failed to append custom auto-gen data to new script!");
                return;
            }

            string namespaceReplacement = GetNamespaceReplacement(filePath, indexOfStartOfFileName);

            UpdateFileContent(ref fileContent, namespaceReplacement);

            File.WriteAllText(filePath, fileContent);
            AssetDatabase.Refresh();
        }

        private static string GetNamespaceReplacement(string filePath, int indexOfStartOfFileName)
        {
            string namespaceReplacement = filePath.Substring(0, indexOfStartOfFileName).Replace('/', '.');

            if (namespaceReplacement.StartsWith("Assets.Scripts.", StringComparison.OrdinalIgnoreCase))
            {
                namespaceReplacement = namespaceReplacement.Substring("Assets.Scripts.".Length);
            }
            else if (namespaceReplacement.Equals("Assets.Scripts", StringComparison.OrdinalIgnoreCase) || namespaceReplacement.Equals("Assets", StringComparison.OrdinalIgnoreCase))
            {
                namespaceReplacement = "";
            }
            else if (namespaceReplacement.StartsWith("Assets."))
            {
                namespaceReplacement = namespaceReplacement.Substring("Assets.".Length);
            }

            return string.IsNullOrEmpty(namespaceReplacement) ? "CCG.Bigfoot" : "CCG.Bigfoot." + namespaceReplacement;
        }

        private static void UpdateFileContent(ref string fileContent, string namespaceReplacement)
        {
            fileContent = fileContent.Replace("#CREATIONDATE#", System.DateTime.Now.ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo));
            fileContent = fileContent.Replace("#NAMESPACE#", namespaceReplacement);
        }
    }
}