Unity Add Default Namespace to Script Template?

2020-07-09 10:32发布

I got a question. I just found Unitys Script template for C# Scripts. And to get the Script name you write #SCRIPTNAME# so it looks like this:

using UnityEngine;
using System.Collections;

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

    }

    void Update () 
    {

    }
}

Than it would create the script with the right name, but is there somthing like #FOLDERNAME# So I can put it in the right namespace dirrectly when creating the script?

标签: c# unity3d
3条回答
戒情不戒烟
2楼-- · 2020-07-09 10:48

There is no built-in template variables like #FOLDERNAME#.

According to this post, there are only 3 magic variables.

  • "#NAME#"
  • "#SCRIPTNAME#"
  • "#SCRIPTNAME_LOWER#"

But you can always hook into the creation process of a script and append the namespace yourself using AssetModificationProcessor.

Here is an example that adds some custom data to the created script.

//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();
   }
}
查看更多
▲ chillily
3楼-- · 2020-07-09 10:49

Using zwcloud's answer and some other resources I was able to generate a namespace on my script files:

First step, navigate:

Unity's default templates can be found under your Unity installation's directory in Editor\Data\Resources\ScriptTemplates for Windows and /Contents/Resources/ScriptTemplates for OSX.

And open the file 81-C# Script-NewBehaviourScript.cs.txt

And make the following change:

namespace #NAMESPACE# {

At the top and

}

At the bottom. Indent the rest so that the whitespace is as desired. Don't save this just yet. If you wish, you can make other changes to the template, such as removing the default comments, making Update() and Start() private, or even removing them entirely.

Again, do not save this file yet or Unity will throw an error on the next step. If you saved, just hit ctrl-Z to undo and then resave, then ctrl-Y to re-apply the changes.

Now create a new script inside an Editor folder inside your Unity Assets directory and call it AddNameSpace. Replace the contents with this:

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();
    }
}

Save this script as well as saving the changes to 81-C# Script-NewBehaviourScript.cs.txt

And you're done! You can test it by creating a new C# script inside any series of folders inside Assets and it will generate the new namespace definition we created.

查看更多
来,给爷笑一个
4楼-- · 2020-07-09 11:08

OK, so this question was already answered by two wonderful people, zwcloud and Draco18s, and their solution works, I'm just showing another version of the same code that, I hope, will be a little more clear in terms of what exactly happening.

Quick notes:

  • Yes, in this method we are getting not the actual file path, but the path of its meta file as a parameter

  • No, you can not use AssetModificationProcessor without UnityEditor prefix, it is deprecated

  • OnWillCreateAsset method is not shown via Ctrl+Shift+M, 'override' typing or base class metadata

_

using UnityEditor;
using System.IO;

public class ScriptTemplateKeywordReplacer : UnityEditor.AssetModificationProcessor
{
    //If there would be more than one keyword to replace, add a Dictionary

    public static void OnWillCreateAsset(string metaFilePath)
    {
        string fileName = Path.GetFileNameWithoutExtension(metaFilePath);

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


        string actualFilePath = $"{Path.GetDirectoryName(metaFilePath)}\\{fileName}";

        string content = File.ReadAllText(actualFilePath);
        string newcontent = content.Replace("#PROJECTNAME#", PlayerSettings.productName);

        if (content != newcontent)
        {
            File.WriteAllText(actualFilePath, newcontent);
            AssetDatabase.Refresh();
        }
    }
}

And this is the contents of my file c:\Program Files\Unity\Editor\Data\Resources\ScriptTemplates\81-C# Script-NewBehaviourScript.cs.txt

using UnityEngine;

namespace #PROJECTNAME#
{

    public class #SCRIPTNAME# : MonoBehaviour
    {
        // Start is called before the first frame update
        void Start()
        {

        }

        // Update is called once per frame
        void Update()
        {

        }
    }
}
查看更多
登录 后发表回答