下午看到有这样需求,然后想到前些天做的去除窗口标题,应该是类似的效果,就去试了下。
使用场景,接手别人的项目时,需要同时开两个或多个项目进行运行对比,由于项目名一样,编辑器版本一样,无法区分,所以需要修改编辑器窗口标题依次来区分。
最初想到的是直接在editor模式下修改标题即可,结果发现,当编辑器切换到运行以及编辑器切换到结束状态时,标题都会重置。所以需要监听状态,修改标题,可以用EditorApplication.playModeStateChanged监听编辑器的状态改变。代码如下,两个脚本,一个editor,一个mono,之所以需要mono,是因为当把前面的监听写到editor脚本里时,当编辑器运行时,这个事件就丢失了。与EditorApplication.update一样。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
using UnityEditor;
using System;
public class SetWindowTitleEditor
{
[MenuItem("CustomTool/SetWindowTitle")]
public static void SetWindowTitleMethod()
{
var values = GameObject.FindObjectsOfType<SetWindowTitleMoNo>();
SetWindowTitleMoNo obj;
if (values.Length > 1)
{
for (int i = values.Length -1 ; i > 0 ; i--)
{
GameObject.DestroyImmediate(values[i].gameObject);
}
obj = values[0];
}
else if (values.Length == 1)
{
obj = values[0];
}
else
{
obj = new GameObject().AddComponent<SetWindowTitleMoNo>();
}
obj.name = "SetWindowTitleMoNo";
obj.SetWindowText();
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Runtime.InteropServices;
using System;
using System.Text;
#if UNITY_EDITOR
public class SetWindowTitleMoNo : MonoBehaviour
{
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();//获取当前窗口
[DllImport("user32.dll", EntryPoint = "SetWindowText")]
static extern int SetWindowText(IntPtr hwnd, string title);//设置窗口标题,参数 句柄,标题
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hwnd, StringBuilder builder,int maxCount);//获取窗口标题
private StringBuilder windowOldTitle;//窗口原标题
[Header("默认标题")]
public string DefaultTitle = "?????";
[Header("从运行状态退出,进入编辑器模式时是否重置为窗口原标题")]
public bool ResetTitleWithQuit = true;
[Header("是否将设置标题作为原标题结尾,设置为true时,标题为 原标题 + DefaultTitle,否则标题为 DefaultTitle")]
public bool TitleIsExt = false;
void Start()
{
windowOldTitle = new StringBuilder(1024);
GetWindowText(GetForegroundWindow(), windowOldTitle, windowOldTitle.Capacity);
Debug.LogError(windowOldTitle.ToString());
SetWindowText();
DontDestroyOnLoad(this);
EditorApplication.playModeStateChanged += modeChange;
Application.quitting += quitting;//执行时间 早于 EditorApplication.playModeStateChanged
}
private void quitting()
{
//SetWindowText();
}
private void modeChange(PlayModeStateChange state)
{
if (state == PlayModeStateChange.EnteredEditMode)//进入编辑器模式
{
if (!ResetTitleWithQuit)
{
SetWindowText();
}
}
}
public void SetWindowText()
{
if (windowOldTitle == null)
{
windowOldTitle = new StringBuilder(1024);
GetWindowText(GetForegroundWindow(), windowOldTitle, windowOldTitle.Capacity);
}
SetWindowText(GetForegroundWindow(), TitleIsExt? $"{windowOldTitle}___{DefaultTitle}" : DefaultTitle);
}
}
#endif
效果如图