大多數時候 我做的unity工具都是一次性的,也就是在場景中操作,關閉unity再打開,或者關閉工具再打開的時候,都沒有儲存工具上的操作資料;如圖:
這是在unity裡面拖拽兩張貼圖上去,然後就可以對這兩張貼圖做各種處理 處理完将貼圖儲存進unity,但是如果我下次打開的時候,我這兩張貼圖已經丢失了,又是下面的這種狀态,也就是說這些資料沒有被保留在工具裡。現在想做的就是希望下次打開的時候,上次操作過的兩張圖還在上面
需要用的知識是: EditorPrefs.SetString EditorPrefs.SetFloat EditorPrefs.SetInt EditorPrefs.SetBool
EditorPrefs.GetString EditorPrefs.GetFloat EditorPrefs.GetInt EditorPrefs.GetBool
有四種類型可以被儲存,比如我們要儲存圖檔,那麼我們可以把圖檔的path以string的方式來儲存,當打開工具初始化的時候,按照儲存的路徑将貼圖執行個體化出來就可以了
代碼如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class TextureCombine : EditorWindow
{
//定義兩張貼圖
Texture2D tex1;
Texture2D tex2;
//儲存資料的path
//--------------------------------------
string path01 = "";
string path02 = "";
const string save01 = "savepath01";
const string save02 = "savepath02";
//--------------------------------------
[MenuItem("Tools/儲存資料")]
static void window()
{
TextureCombine win = (TextureCombine)EditorWindow.GetWindow(typeof(TextureCombine), false, "合并貼圖", false);
win.position = new Rect(200, 200, 250, 200);
win.Show();
}
//打開工具時候就開始初始化 取出儲存的路徑 然後将貼圖根據路徑初始化
//---------------------------------------------
void OnEnable()
{
path01 = EditorPrefs.GetString(save01, path01);
path02 = EditorPrefs.GetString(save02, path02);
tex1 = (Texture2D)AssetDatabase.LoadAssetAtPath<Texture2D>(path01);
tex2 = (Texture2D)AssetDatabase.LoadAssetAtPath<Texture2D>(path02);
}
//-------------------------------------------
private void OnGUI()
{
GUILayout.BeginVertical();
{
GUILayout.BeginHorizontal();
{
GUILayout.Space(180);
EditorGUILayout.LabelField("偏色貼圖");
}
GUILayout.EndHorizontal();
tex1 = EditorGUILayout.ObjectField("", tex1, typeof(Texture2D), true) as Texture2D;
GUILayout.BeginHorizontal();
{
GUILayout.Space(180);
EditorGUILayout.LabelField("高光貼圖");
}
GUILayout.EndHorizontal();
tex2 = EditorGUILayout.ObjectField("", tex2, typeof(Texture2D), true) as Texture2D;
}
GUILayout.EndVertical();
if (GUI.Button(new Rect(173, 173, 70, 20), "save"))
{
if (tex1!=null && tex2 != null)
{
//取到拖進去的兩張圖檔的路徑 并儲存
//----------------------------------------------------
path01 = AssetDatabase.GetAssetPath(tex1);
path02 = AssetDatabase.GetAssetPath(tex2);
EditorPrefs.SetString(save01, path01);
EditorPrefs.SetString(save02, path02);
//-----------------------------------------------------
}
else
this.ShowNotification(new GUIContent("沒有貼圖"));
}
}
}
點save的時候 這兩張圖檔就永遠被保留在本地機器上
最近在研究一個工具:将一部分數值永久記錄下來 然後指派給每個新的物體,就用了這個方法。這樣友善美術
不然還的美術每次開始用工具的時候,先輸入一遍數值,以關掉下次又得輸入一次 比較麻煩
親,如果您覺得本文不錯,願意給我一些動力的話,請用手機掃描二維碼即可向我打賞