Extending the script template for the Unity3d editor

Source: Internet
Author: User
Tags lua

?? Recently in learning shader feeling shader language, grammatical strange, assuming every time you start writing shader must be a painful thing. It is assumed that a standard set of shader templates can be defined locally, so that when we need to implement some shader with similar effects, we can make changes on the basis of this shader template.

Since the shader file is a text file, we are able to easily create such a template, in this template we can further intact related to the reference gaze, so that you do not have to write shader every time you need to check the document, from this point of view, has entered the topic of this article: extending the script template of the Unity3d editor.

Retrace, where are the templates?

?? Unity3d The default script template is located under the/editor/data/resources/scripttemplates/folder, note that the folder is relative to the Unity3d installation folder, In this folder we can find some clues to the script template in Unity3d, first of all, the script template is a simple text file, the text file is pre-populated with content, When we create a modulo script or shader in the editor, we actually read the files and then write them to the specified path in the project.

Secondly. These template files are labeled #scriptname# or #name#. When we create a file in the editor, this tag is replaced with the specified file name. For example, a script that inherits from Monobehaviour in Unity3d. One important feature is that the file name must be consistent with the class name. This is certainly a setting for the Unity3d engine, but there is also a reason to be able to justify it here.

We notice that there is a unique number in the file name of these templates, such as the number in the template of the C # script is 81, the number in the shader template is 83, what are these numbers, which the blogger calls the black technology from the stars.

Black technology from the stars

?? As a person who often tinkering with unity3d editors. Let's say you don't know MenuItem, Editorwindow, Scriptablewizard these black technologies. That means you are not a person who likes to toss and explore.

From the Unity3d API documentation, we know that the MenuItem prototype is:

MenuItem(string itemName,bool isValidateFunction,int

I know what we usually use MenuItem is its first parameter, which defines the name of a menu item, and we can use the "/" delimiter to represent the hierarchy of the menus. MenuItem needs to be used in conjunction with a static method, which can be understood as the code in a static method is run when we click on the currently defined menu. So MenuItem is often able to help us do some of the work of editor extension development. OK, the second parameter as a validation flag. Assuming that the flag is true, it means that the static method we define is a validation method that validates the method first before running the static method, which we'll take for the time being, because today we have a black technology from the stars that is mainly related to the third parameter, and the third one represents a priority, It represents the order in which the menu items are displayed in the menu bar, the priority menu items are displayed below the priority menu item, so we are clear about the true meaning of the number similar to 81, 83 in the template file name, and note that the order of the template files is the same as the order of the menu items in the editor, and we make an attempt. Write the following code:

[MenuItem ("Assets/create/lua Scripts",false, -)]Static voidCreateluascripts () {}[menuitem ("assets/create/fixed function shader",false, the)]Static voidCreatefixedfunctionshader () {}[menuitem ("assets/create/surface shader",false, the)]Static voidCreatesurfaceshader () {}[menuitem ("assets/create/programmable shader",false, the)]Static voidCreatevertexandfragmentshader () {}

Notice that we continue to write four methods according to the known priority, and now we can find the default menu bar changed in the editor:

We can see that the four menus we've written are in effect, even though they're not going to do anything at all. But in this direction to explore, we can achieve the original dream.

Now we're thinking about how to create a file based on a template, which is simply too simple for us to read the template through StreamReader. You can then use StreamWriter to generate the file.

However, the file name of the created file is fixed. We can't change the file when we create it. And even changing the name defined in the file does not change. So we need a better solution. Unity3d provides a Unityeditor.projectwindowcallback namespace that provides a class called endnameeditaction in this space, and we simply have to inherit this class to complete the task. This class needs to rewrite the action method, and we know that the complete step to create a file is to create the file and then highlight it, so this part of the code is implemented like this:

//   <summary> ///   Define an action class that creates a resource and implement its action method//   </summary> Class createassetaction:endnameeditaction{ Public Override void Action(intInstanceId,stringPathName,stringResourcefile) {//Create a resourceObject obj = createassetformtemplate (pathName, resourcefile);//Highlight the resourceProjectwindowutil.showcreatedasset (obj); }Internal StaticObjectcreateassetformtemplate(stringPathName,stringResourcefile) {//Get the absolute path to create the resource        stringFullName = Path.GetFullPath (pathName);//Read local template fileStreamReader reader =NewStreamReader (resourcefile);stringContent = Reader.        ReadToEnd (); Reader. Close ();//Get the file name of the resource        stringFileName = Path.getfilenamewithoutextension (pathName);//Replace the default file nameContent = content. Replace ("#NAME", fileName);//write new fileStreamWriter writer =NewStreamWriter (FullName,false, System.Text.Encoding.UTF8); Writer.        Write (content); Writer. Close ();//Refresh Local ResourcesAssetdatabase.importasset (PathName); Assetdatabase.refresh ();returnAssetdatabase.loadassetatpath (PathName,typeof(Object)); }}

This part of the code is relatively simple, is to read the local template file and then generate a new file, the new file will be generated when the #name replaced with the actual file name, so we finished the file resource creation.

The question now is how to get the actual path when creating the file, and this part of the code is implemented like this:

Private Static string Getselectedpath(){//default path is assets    stringSelectedPath ="Assets";//Get the selected resourceobject[] selection = selection.getfiltered (typeof(Object), selectionmode.assets);//Traverse the selected resource to return the path    foreach(Object objinchSelection) {SelectedPath = Assetdatabase.getassetpath (obj);if(!string. IsNullOrEmpty (SelectedPath) && file.exists (SelectedPath)) {SelectedPath = Path.getdirectoryname (SelectedPath); Break; }    }returnSelectedPath;}

The problem of creating resources is now being conquered. We'll just call Projectwindowutil's Startnameeditingifprojectwindowexists method next. The method needs to pass in an instance of a class that inherits from Endnameeditaction, the path to the destination file, and the template file.

For example, to create a LUA script that can be implemented:

[MenuItem("Assets/Create/Lua Scripts"false85)]staticvoid CreateLuaScripts(){    ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0,        ScriptableObject.CreateInstance<CreateAssetAction>(),        "/NewLuaScript.lua"null,        "Assets/Editor/Template/85-Lua-NewLuaScript.lua.txt");}
Summary

?? Now with this black technology, we can create a lot of other templates to extend the functionality of the editor, for example, for shader, we can create basic shader templates, And then every time you need to write shader directly from the template library to choose a function similar shader and then change, so than start from scratch to write a new shader should be much easier, this period of time to learn shader, feel the process slowly away from the master of Graphics, line, That's the way this blog post is.

Extending the script template for the Unity3d editor

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.