Unity默认使用的编译器VisualStudio带有扩展插件ShaderLabVS,但功能很差,所以还是选用VisualStudioCode作为编写Shader的编译器,一方面其能自动识别Shaderlab语法,并且还有丰富的Shader扩展插件来辅助编写。
实际上编写时我们只希望.shader文件有VSCODE打开,其他脚本正常还是用VS,可以通过Editor.Callbacks的特性来完成。
using System;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine;
public class ShaderEditor
{
[OnOpenAssetAttribute(1)]
public static bool step1(int instanceID, int line)
{
string path = AssetDatabase.GetAssetPath(EditorUtility.InstanceIDToObject(instanceID));
string name = Application.dataPath + "/" + path.Replace("Assets/", "");
if (name.EndsWith(".shader")) //文件扩展名类型
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "C:/Users/Administrator/AppData/Local/Programs/Microsoft VS Code/Code.exe"; //VSCODE程序
startInfo.Arguments = name;
process.StartInfo = startInfo;
process.Start();
return true;
}
return false;
}
}
将startInfo.FileName替换成自己VSCODE的路径即可,这里不建议使用环境变量,Windows自带的路径是\而C#启用的地址是/,这里转换比较麻烦,不如直接写明。 使用的时候将这个脚本放在Editor文件下即可,新打开项目时,需要在ShaderEditor里面敲个空行重新编译才能使用(如果没反应先把VSCode打开)。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class ShaderVS
{
[MenuItem("Tools/启用VSCode编辑Shader文件")]
public static void OpenVSCode()
{
UnityEditor.Compilation.CompilationPipeline.RequestScriptCompilation();
}
}
写个Menu进项目强制重新编译下。