IntSlider callback function? Editor Scripting

微笑、不失礼 提交于 2019-12-11 04:45:06

问题


I just got into Editor Scripting recently and I'm still getting a hold of all the basics. I wanted to know if the IntSlider (that we use to create a slider of integer values) has any methods or functions that can be used to get more functionality?

Something like the Slider class:
You have -maxValue, -minValue, -value, -onValueChanged (Callback executed when the value of the slider is changed)

These work during the "Play" mode.

I need to access this information while in the editor. Specifically: I need to access the onValueChanged (if it exists) of the IntSlider so I can assign a function for it to execute.

IntSlider Code:

totalRooms = EditorGUILayout.IntSlider(new GUIContent ("Total Rooms"), totalRooms, 0, 10);

Is there a way to achieve this for the inspector? Or something that can be created to solve this? If you can point me in the right direction, I'd be grateful.

I'm using Unity 5.3.1f


回答1:


There is no such event in Unity at the moment. However this can be implemented easily like this:

Add a UnityEvent in your actual script.

public UnityEvent OnVariablesValueChanged;

Then in your editor script check if value is changed. (Note: I tried to write easily understandable code sample for this. you can change it accordingly)

[CustomEditor(typeof(MyScript))]
public class MyScriptEditor : Editor 
{
    public override void OnInspectorGUI()
    {
        MyScript myTarget = (MyScript)target;
        int prevValue = myTarget.variable;
        myTarget.variable = EditorGUI.IntSlider(new Rect(0,0,100, 20), prevValue, 1, 10);
        int newValue = myTarget.variable;
        if (prevValue != newValue)
        {
            Debug.Log("New value of variable is  :" + myTarget.variable);
            myTarget.OnVariablesValueChanged.Invoke();
        }
        base.OnInspectorGUI();
    }
}

Then add listener to OnVariablesValueChanged event from inspector.

Hope this helps.



来源:https://stackoverflow.com/questions/39598551/intslider-callback-function-editor-scripting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!