快速添加命名空间

方法一: 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
 
/// <summary>
/// 给脚本添加和修改命名空间
/// </summary>
public class AddNamespaceTool : ScriptableWizard {
 
	public string folder="Assets/";
	public string namespaceName;
 
	void OnEnable(){
		if(Selection.activeObject != null)
		{
			string dirPath = AssetDatabase.GetAssetOrScenePath(Selection.activeObject);
			if(File.Exists(dirPath)){
				dirPath = dirPath.Substring(0,dirPath.LastIndexOf("/"));
			}
			folder = dirPath;
		}
	}
 
	[MenuItem("Comb Project/Add Namespace",false,10)]
	static void CreateWizard () {
		AddNamespaceTool editor = ScriptableWizard.DisplayWizard<AddNamespaceTool>("Add Namespace", "Add");
		editor.minSize = new Vector2(300,200);
	}
	public void OnWizardCreate(){
		//save settting
 
		if(!string.IsNullOrEmpty(folder) && !string.IsNullOrEmpty(namespaceName))
		{
 
			List<string> filesPaths = new List<string>();
			filesPaths.AddRange(
				Directory.GetFiles(Path.GetFullPath(".") + Path.DirectorySeparatorChar + folder, "*.cs", SearchOption.AllDirectories)
			);
			Dictionary<string,bool> scripts = new Dictionary<string, bool>();
 
			int counter = -1;
			foreach (string filePath in filesPaths) {
 
				scripts[filePath] = true;
 
				EditorUtility.DisplayProgressBar("Add Namespace", filePath, counter / (float) filesPaths.Count);
				counter++;
		
				string contents = File.ReadAllText(filePath);
 
				string result = "";
				bool havsNS = contents.Contains("namespace ");
				string t = havsNS ? "" : "\t";
 
				using(TextReader reader = new StringReader(contents))
				{
					int index = 0;
					bool addedNS = false;
					while (reader.Peek() != -1)
					{
						string line = reader.ReadLine();
 
						if(line.IndexOf("using")>-1 || line.Contains("#")){
							result += line+"\n";
						}else if(!addedNS && !havsNS){
							result += "\nnamespace "+namespaceName+" {";
							addedNS = true;
							result += t+line+"\n";
						}else{
							if(havsNS && line.Contains("namespace ")){
								if(line.Contains("{")){
									result += "namespace "+namespaceName+" {\n";
								}else{
									result += "namespace "+namespaceName+"\n";
								}
							}
							else
							{
								result += t+line+"\n";
							}
						}
						++index;
					}
					reader.Close();
				}
				if(!havsNS){
					result += "}";
				}
				File.WriteAllText(filePath, result);
			}
 
 
 
			//处理加了命名空间后出现方法miss
			filesPaths.AddRange(
				Directory.GetFiles(Path.GetFullPath(".") + Path.DirectorySeparatorChar + folder, "*.unnity", SearchOption.AllDirectories)
			);
			filesPaths.AddRange(
				Directory.GetFiles(Path.GetFullPath(".") + Path.DirectorySeparatorChar + folder, "*.prefab", SearchOption.AllDirectories)
			);
 
 
			counter = -1;
			foreach (string filePath in filesPaths) {
				EditorUtility.DisplayProgressBar("Modify Script Ref", filePath, counter / (float) filesPaths.Count);
				counter++;
 
				string contents = File.ReadAllText(filePath);
 
				string result = "";
				using(TextReader reader = new StringReader(contents))
				{
					int index = 0;
					bool addedNS = false;
					while (reader.Peek() != -1)
					{
						string line = reader.ReadLine();
 
						if(line.IndexOf("m_ObjectArgumentAssemblyTypeName:")>-1 && !line.Contains(namespaceName)){
 
							string scriptName = line.Split(':')[1].Split(',')[0].Trim();
							if(scripts.ContainsKey(scriptName))
							{
								line = line.Replace(scriptName,"namespaceName."+scriptName);
							}
 
							result += line+"\n";
						}else{
							result += line+"\n";
						}
						++index;
					}
					reader.Close();
				}
 
				File.WriteAllText(filePath, result);
			}
 
 
			EditorUtility.ClearProgressBar();
			AssetDatabase.Refresh();
		}
	}
}

方法二:

using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;

public class Test : MonoBehaviour
{
    public static string startStr = "\nnamespace Test{";
    public static string endStr = "\n}";


    public static string checkStr = "public class";
    public static string spaceName = "namespace Test";


    public static string rootName = "/Scripts";


    [MenuItem("Assets/AutoAddNameSpace")]
    public static void AutoAddNameSpace()
    {
        CheckFileName(Application.dataPath + rootName);
    }



    public static void CheckFileName(string dataPath)
    {
        foreach (var item in Directory.GetFiles(dataPath))
        {
            if (item.Contains(".cs") && !item.Contains(".meta"))
            {
                if (!ContainNameSpace(item))
                {
                    AddNameSpace(item);
                }
            }
        }


        foreach (var item in Directory.GetDirectories(dataPath))
        {
            CheckFileName(item);
        }
    }




    public static bool ContainNameSpace(string path)
    {
        StreamReader sr_check = new StreamReader(path);
        string all = sr_check.ReadToEnd();


        sr_check.Close();
        return all.Contains(spaceName);
    }


    public static void AddNameSpace(string path)
    {
        StreamReader sr = new StreamReader(path);
        StringBuilder sb = new StringBuilder();


        string line;
        int lineIndex = 0;


        while ((line = sr.ReadLine()) != null)
        {
            if (line.Contains(checkStr))
            {
                sb.Append(startStr);
            }
            if (lineIndex == 0)
                sb.Append(line);
            else
                sb.Append("\n" + line);
            lineIndex++;
        }


        sb.Append(endStr);


        sr.Close();


        StreamWriter sw = new StreamWriter(path);
        sw.WriteLine(sb.ToString());


        sw.Close();
    }
}

使用完流之后 需要将流关闭,否则会出现无法访问文件的情况。因为此时文件正在被流占用。

 

相关连接:
https://blog.csdn.net/douniwan08/article/details/78465152

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值