【unity小技巧之四】变量弹出SortingLayer选择面板

经常想在脚本中设置一个变量对应SortingLayer的某个层,然后赋值给SpriteRender修改排序层,但是unity官方似乎没有办法直接弹出SortingLayer面板进行选择,就像是LayerMask一样。

public LayerMask hurtLayer;

既然unity不内置,那就自己想办法通过PropertyAttribute来实现吧,脚本中只要在变量声明前面用"[]"括起来即可实现

[Range(0f,1f)]
public float linerDrag = 0.2f;
比如上面这些就是是unity内置PropertyAttribute,照着这个思路,我们来看看怎么实现SortingLayer选择面板。

ps:什么是自定义属性?见Unity 扩展属性自定义绘制


先写一个PropertyAttribute类

using UnityEngine;
using System.Collections;

public class SortingLayerAttribute : PropertyAttribute {

	public SortingLayerAttribute(){
	}
}

对应写属性绘制类:(解析该自定义属性,在Inspector进行GUI的绘制)

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Reflection;
using UnityEditorInternal;
using System;

[CustomPropertyDrawer(typeof(SortingLayerAttribute))]
public class SortingLayerDrawer : PropertyDrawer {
	const string NONE = "<None>";

	public override void OnGUI (Rect position, SerializedProperty property, GUIContent label)
	{
		if (property.propertyType != SerializedPropertyType.String) {
			EditorGUI.LabelField(position, "ERROR:", "May only apply to type string");
			return;
		}
		position = EditorGUI.PrefixLabel(position, label);
		string value = property.stringValue;
		if (string.IsNullOrEmpty (value))
			value = NONE;
		if (GUI.Button(position, value, EditorStyles.popup)) {
			Selector(property);
		}
	}

	void Selector(SerializedProperty property) {
		string[] layers = GetSortingLayerNames ();

		GenericMenu menu = new GenericMenu();

		bool isNone = string.IsNullOrEmpty (property.stringValue);
		menu.AddItem(new GUIContent(NONE), isNone, HandleSelect, new SpineDrawerValuePair(NONE, property));

		for (int i = 0; i < layers.Length; i++) {
			string name = layers[i];
			menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
		}
		menu.ShowAsContext();
	}

	void HandleSelect(object val) {
		var pair = (SpineDrawerValuePair)val;
		if (pair.str.Equals (NONE)) {
			pair.property.stringValue = "";
		} else {
			pair.property.stringValue = pair.str;
		}
		pair.property.serializedObject.ApplyModifiedProperties();
	}

	// Get the sorting layer names
	public string[] GetSortingLayerNames() {
		Type internalEditorUtilityType = typeof(InternalEditorUtility);
		PropertyInfo sortingLayersProperty = internalEditorUtilityType.GetProperty("sortingLayerNames", BindingFlags.Static | BindingFlags.NonPublic);
		return (string[])sortingLayersProperty.GetValue(null, new object[0]);
	}
}

实现后的效果如下:




记住:SortingLayerDrawer.cs是编辑器类,请放在Editor目录下才能生效,SortingLayerAttribute.cs随意放即可

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鱼蛋-Felix

如果对你有用,可以请我喝杯可乐

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值