版本: Unity 6 (6000.0)
语言English
  • C#

HandleUtility.AddControl

建议更改

成功!

感谢您帮助我们提高 Unity 文档的质量。虽然我们无法采纳所有提交内容,但我们确实阅读了用户提出的每个建议更改,并在适用情况下进行更新。

关闭

提交失败

由于某些原因,您的建议更改无法提交。请<a>稍后再试</a>。感谢您抽出时间帮助我们提高 Unity 文档的质量。

关闭

取消

声明

public static void AddControl(int controlId, float distance);

参数

controlId 如果鼠标光标靠近句柄,则记录为最近控件的 ID。
distance 从鼠标光标到句柄的距离。

描述

记录来自句柄的距离测量值。

所有句柄在布局期间都会使用其 controlID 调用此方法,然后使用 nearestControl 检查它们是否获得了鼠标按下事件。

using UnityEngine;
using UnityEditor;

public class ExampleScript : MonoBehaviour
{
    public float value = 1.0f;
}

// A tiny custom editor for ExampleScript component.
[CustomEditor(typeof(ExampleScript))]
public class ExampleEditor : Editor
{
    // Custom in-scene UI for when ExampleScript component is selected.
    public void OnSceneGUI()
    {
        var controlID = GUIUtility.GetControlID(FocusType.Passive);
        var evt = Event.current;

        var t = target as ExampleScript;
        var tr = t.transform;
        var pos = tr.position;

        switch (evt.GetTypeForControl(controlID))
        {
            case EventType.Layout:
            case EventType.MouseMove:
                // Set the nearest control ID to "controlID" if the mouse cursor is
                // near or directly above the solid disc handle.
                var distanceToHandle = HandleUtility.DistanceToCircle(pos, t.value);
                HandleUtility.AddControl(controlID, distanceToHandle);
                break;
            case EventType.MouseDown:
                // Log the nearest control ID if the click is near or directly above
                // the solid disc handle.
                if (controlID == HandleUtility.nearestControl && evt.button == 0)
                {
                    Debug.Log($"The nearest control is {controlID}.");

                    GUIUtility.hotControl = controlID;
                    evt.Use();
                }
                break;
            case EventType.MouseUp:
                if (GUIUtility.hotControl == controlID && evt.button == 0)
                {
                    GUIUtility.hotControl = 0;
                    evt.Use();
                }
                break;
            case EventType.Repaint:
                // Display an orange solid disc where the object is.
                Handles.color = new Color(1, 0.8f, 0.4f, 1);
                Handles.DrawSolidDisc(pos, tr.up, t.value);
                break;
        }
    }
}