Unity琐碎(1) 编辑器参数修改

今天在写编辑器面板的时候,突然发现如果面板参数变化的时候,不能实时修改表现效果(参数没有生效)。

public int monsterCount  ;
void Awake() 
{
	monsterCount = Mathf.Clamp(monsterCount, 0, 1000);
}

就像上面的代码,只在启动的时候的会修改变量的数值,运行中修改编辑器中参数不会再去执行Awake的....

解决思路

(1) MonoBehavior.OnValidate()

his function is called when the script is loaded or a value is changed in the inspector (Called in the editor only).

Use this function to validate the data of your MonoBehaviours. This can be used to ensure that when you modify date in an editor that the data stays within a certain range.

(2) 自定义编辑器
在自定义编辑器中访问更新数据相关的接口(代码不准确,意思表达清晰即可)

public int monsterCount  ;
public int MonsterCount
{
	set{monsterCount   = value ; UpdateParam() ;}
}

void Awake() 
{
	monsterCount = Mathf.Clamp(monsterCount, 0, 1000);
}

void UpdateParam()
{
	monsterCount = Mathf.Clamp(monsterCount, 0, 1000);
}

附加

有些代码逻辑在Awake中不实现的,也可以尝试定义[[ExecuteInEditMode ]]解决(https://docs.unity3d.com/ScriptReference/ExecuteInEditMode.html)解决编辑器下的问题。

posted @ 2017-03-19 16:35  RubbyZhang  阅读(1562)  评论(0编辑  收藏  举报