Unity将默认命名空间添加到脚本模板?

Joa*_*son 5 c# unity-game-engine

我有一个问题.我刚刚找到了C#Scripts的Unitys Script模板.要获得您编写的脚本名称#SCRIPTNAME#,它看起来像这样:

using UnityEngine;
using System.Collections;

public class #SCRIPTNAME# : MonoBehaviour 
{
    void Start () 
    {

    }

    void Update () 
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

比它创建具有正确名称的脚本,但有没有像#FOLDERNAME那样的东西#所以我可以在创建脚本时直接将它放在正确的命名空间中?

Ada*_*val 11

我知道这是一个老问题,但在较新版本的 Unity 中,您可以定义要在项目中使用的根命名空间。您可以在“编辑”>“项目设置”>“编辑器”>“根命名空间”中定义命名空间

这样做将在新创建的脚本上添加定义的名称空间。

  • 您还可以将命名空间添加到要使用的程序集中,并且该程序集中所有新创建的文件都将具有程序集命名空间 (2认同)

zwc*_*oud 6

没有像#FOLDERNAME#这样的内置模板变量.

根据这篇文章,只有3个魔术变量.

  • "#名称#"
  • "#SCRIPTNAME#"
  • "#SCRIPTNAME_LOWER#"

但是你总是可以挂钩脚本的创建过程并使用自己附加命名空间AssetModificationProcessor.

是一个向创建的脚本添加一些自定义数据的示例.

//Assets/Editor/KeywordReplace.cs
using UnityEngine;
using UnityEditor;
using System.Collections;

public class KeywordReplace : UnityEditor.AssetModificationProcessor
{

   public static void OnWillCreateAsset ( string path )
   {
     path = path.Replace( ".meta", "" );
     int index = path.LastIndexOf( "." );
     string file = path.Substring( index );
     if ( file != ".cs" && file != ".js" && file != ".boo" ) return;
     index = Application.dataPath.LastIndexOf( "Assets" );
     path = Application.dataPath.Substring( 0, index ) + path;
     file = System.IO.File.ReadAllText( path );

     file = file.Replace( "#CREATIONDATE#", System.DateTime.Now + "" );
     file = file.Replace( "#PROJECTNAME#", PlayerSettings.productName );
     file = file.Replace( "#SMARTDEVELOPERS#", PlayerSettings.companyName );

     System.IO.File.WriteAllText( path, file );
     AssetDatabase.Refresh();
   }
}
Run Code Online (Sandbox Code Playgroud)


Dra*_*18s 6

使用 zwcloud 的答案和其他一些资源,我能够在我的脚本文件上生成一个命名空间:

第一步,导航:

Unity 的默认模板可以在Editor\Data\Resources\ScriptTemplatesWindows 和/Contents/Resources/ScriptTemplatesOSX 的Unity 安装目录下找到。

并打开文件 81-C# Script-NewBehaviourScript.cs.txt

并进行以下更改:

namespace #NAMESPACE# {
Run Code Online (Sandbox Code Playgroud)

在顶部和

}
Run Code Online (Sandbox Code Playgroud)

在底部。缩进其余部分,以便根据需要留出空格。暂时不要保存这个。如果您愿意,您可以对模板进行其他更改,例如删除默认注释、制作Update()Start() private,甚至完全删除它们。

同样,不要保存此文件,否则 Unity 将在下一步中引发错误。如果您保存了,只需按 ctrl-Z 撤消然后重新保存,然后按 ctrl-Y 重新应用更改。

现在在 Unity Assets 目录中的 Editor 文件夹中创建一个新脚本并将其命名为AddNameSpace. 将内容替换为:

using UnityEngine;
using UnityEditor;

public class AddNameSpace : UnityEditor.AssetModificationProcessor {

    public static void OnWillCreateAsset(string path) {
        path = path.Replace(".meta", "");
        int index = path.LastIndexOf(".");
        if(index < 0) return;
        string file = path.Substring(index);
        if(file != ".cs" && file != ".js" && file != ".boo") return;
        index = Application.dataPath.LastIndexOf("Assets");
        path = Application.dataPath.Substring(0, index) + path;
        file = System.IO.File.ReadAllText(path);

        string lastPart = path.Substring(path.IndexOf("Assets"));
        string _namespace = lastPart.Substring(0, lastPart.LastIndexOf('/'));
        _namespace = _namespace.Replace('/', '.');
        file = file.Replace("#NAMESPACE#", _namespace);

        System.IO.File.WriteAllText(path, file);
        AssetDatabase.Refresh();
    }
}
Run Code Online (Sandbox Code Playgroud)

保存此脚本并将更改保存到 81-C# Script-NewBehaviourScript.cs.txt

你完成了!您可以通过在 Assets 内的任何系列文件夹中创建一个新的 C# 脚本来测试它,它将生成我们创建的新命名空间定义。


mrc*_*ted 6

我很清楚这个问题已经被很棒的人回答了(zwcloud、Darco18 和 Alexey)。但是,由于我的命名空间组织遵循项目中的文件夹结构,因此我对代码进行了一些小的修改,我在此处共享它以防有人需要它并且具有与我相同的组织方法米跟随。

请记住,你需要设置根命名空间中的项目设置C#项目生成部。编辑:我已经对代码进行了一些调整,将其放置在脚本、编辑器等的根文件夹中。

public class NamespaceResolver : UnityEditor.AssetModificationProcessor 
    {
        public static void OnWillCreateAsset(string metaFilePath)
        {
            var fileName = Path.GetFileNameWithoutExtension(metaFilePath);

            if (!fileName.EndsWith(".cs"))
                return;

            var actualFile = $"{Path.GetDirectoryName(metaFilePath)}\\{fileName}";
            var segmentedPath = $"{Path.GetDirectoryName(metaFilePath)}".Split(new[] { '\\' }, StringSplitOptions.None);

            var generatedNamespace = "";
            var finalNamespace = "";

            // In case of placing the class at the root of a folder such as (Editor, Scripts, etc...)  
            if (segmentedPath.Length <= 2)
                finalNamespace = EditorSettings.projectGenerationRootNamespace;
            else
            {
                // Skipping the Assets folder and a single subfolder (i.e. Scripts, Editor, Plugins, etc...)
                for (var i = 2; i < segmentedPath.Length; i++)
                {
                    generatedNamespace +=
                        i == segmentedPath.Length - 1
                            ? segmentedPath[i]
                            : segmentedPath[i] + "."; // Don't add '.' at the end of the namespace
                }
                
                finalNamespace = EditorSettings.projectGenerationRootNamespace + "." + generatedNamespace;
            }
            
            var content = File.ReadAllText(actualFile);
            var newContent = content.Replace("#NAMESPACE#", finalNamespace);

            if (content != newContent)
            {
                File.WriteAllText(actualFile, newContent);
                AssetDatabase.Refresh();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)