Unity编辑器中实现GUILayout按钮按下时切换纹理的方法
解决GUILayout按钮切换纹理的问题
核心思路是给每个按钮绑定独立的状态存储,把每个按钮当前选中的纹理索引存在Scriptable Object的矩阵里,这样每次绘制按钮时就能根据矩阵里的索引获取对应纹理,点击时更新索引即可。
步骤1:调整Scriptable Object的存储结构
确保你的Scriptable Object里有两个关键字段:
- 存储每个按钮纹理索引的矩阵(一维数组对应NxN网格,方便序列化)
- 纹理数组(你的Balls纹理集合)
示例Scriptable Object代码:
using UnityEngine; [CreateAssetMenu(fileName = "PatternData", menuName = "Custom/Pattern Data")] public class PatternData : ScriptableObject { public int[] patternMatrix; // 长度为N²,对应NxN按钮网格 public Texture2D[] ballTextures; // 你的纹理数组 }
步骤2:修改编辑器脚本逻辑
在编辑器循环里,每个按钮对应矩阵的一个位置,绘制时读取该位置的索引获取纹理,点击时更新索引并保存修改:
// 获取网格大小(NxN),用RoundToInt避免浮点计算误差 int gridSize = Mathf.RoundToInt(Mathf.Sqrt(script.patternMatrix.Length)); for (int row = 0; row < gridSize; row++) { EditorGUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); EditorGUILayout.LabelField((row + 1).ToString(), GUILayout.MaxWidth(15f), GUILayout.MaxHeight(50f)); EditorGUILayout.BeginHorizontal(); { for (int col = 0; col < gridSize; col++) { // 计算当前按钮在一维数组中的对应索引 int matrixIndex = row * gridSize + col; // 容错处理:避免纹理数组为空导致索引越界 if (script.ballTextures == null || script.ballTextures.Length == 0) { GUILayout.Button("无纹理", GUILayout.Width(50), GUILayout.Height(50)); continue; } // 根据矩阵索引获取当前按钮要显示的纹理 Texture2D currentTexture = script.ballTextures[script.patternMatrix[matrixIndex]]; // 绘制按钮并处理点击事件 if (GUILayout.Button(currentTexture, GUILayout.Width(50), GUILayout.Height(50))) { // 记录撤销操作,支持Ctrl+Z回退 Undo.RecordObject(script, "切换纹理"); // 循环切换纹理:索引+1,超出数组长度则回到0 script.patternMatrix[matrixIndex] = (script.patternMatrix[matrixIndex] + 1) % script.ballTextures.Length; // 标记对象为脏,确保修改能被保存到磁盘 EditorUtility.SetDirty(script); } } } EditorGUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); } EditorGUILayout.EndHorizontal(); }
关键改动说明
- 状态绑定:每个按钮对应
patternMatrix里的一个索引,让按钮状态能持久化存储在Scriptable Object中 - 循环切换逻辑:用取模运算实现纹理循环,点击后自动跳到下一张,到数组末尾时回到第一张
- 编辑器安全处理:增加纹理数组为空的判断避免报错;用
Undo.RecordObject支持撤销操作,EditorUtility.SetDirty确保修改被保存
内容的提问来源于stack exchange,提问作者Yusuf Tahir Orhan
相关产品推荐
相关产品推荐

