FishPlayer

一个喜欢摸鱼的废物

0%

Unity2020 Graphic 小坑

最近项目升级了2020.3,Graphic这边多给了一个Raycast Padding的设置。
我们有在用一些完全空白的图片来接受UI的点击响应,同时也有一些用图片接收点击的按钮。

但很坑爹的是,我发现无论怎么设置Raycast Padding的值,场景预览中都没有显示框框,所以我其实是完全不知道这玩意儿到底怎么用的。
搜索一下才知道原来是padding的数值是负数的时候才是往外扩张。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

public class RaycastTarget : Graphic
{
// Additionally, If you need a Raycast target that is not a rectangle, you can implement bool Raycast(Vector2 sp, Camera eventCamera) method from Graphic.
public override void SetMaterialDirty() { return; }
public override void SetVerticesDirty() { return; }
/// Probably not necessary since the chain of calls `Rebuild()`->`UpdateGeometry()`->`DoMeshGeneration()`->`OnPopulateMesh()` won't happen; so here really just as a fail-safe.
protected override void OnPopulateMesh(VertexHelper vh)
{
vh.Clear();
return;
}

#if UNITY_EDITOR

private void OnDrawGizmos()
{
if (!this.enabled)
return
RectTransform rectTransform = this.transform as RectTransform;
Color wireColor = Color.yellow;
if (this.isActiveAndEnabled)
wireColor.a *= 0.7f
// Padding to be applied to the masking
// X = Left, Y = Bottom, Z = Right, W = Top
// if you wanna make it bigger, then the all value shouble be negative
Vector4 padding = this.raycastPadding * -1.0f;
Matrix4x4 localToWorld = rectTransform.localToWorldMatrix
Vector3 topLeft = SomeUtils.GetOffsetLocalPosition(rectTransform, SomeUtils.UIOffsetType.TopLeft);
Vector3 topRight = SomeUtils.GetOffsetLocalPosition(rectTransform, SomeUtils.UIOffsetType.TopRight);
Vector3 bottomLeft = SomeUtils.GetOffsetLocalPosition(rectTransform, SomeUtils.UIOffsetType.BottomLeft);
Vector3 bottomRight = SomeUtils.GetOffsetLocalPosition(rectTransform, SomeUtils.UIOffsetType.BottomRight)
topLeft = localToWorld.MultiplyPoint(topLeft + (Vector3.left * padding.x) + (Vector3.up * padding.w));
topRight = localToWorld.MultiplyPoint(topRight + (Vector3.right * padding.z) + (Vector3.up * padding.w));
bottomLeft = localToWorld.MultiplyPoint(bottomLeft + (Vector3.left * padding.x) + (Vector3.down * padding.y));
bottomRight = localToWorld.MultiplyPoint(bottomRight + (Vector3.right * padding.z) + (Vector3.down * padding.y))
Color tempColor = Gizmos.color;
Gizmos.color = wireColor
Gizmos.DrawLine(topLeft, topRight);
Gizmos.DrawLine(topLeft, bottomLeft);
Gizmos.DrawLine(bottomRight, topRight);
Gizmos.DrawLine(bottomRight, bottomLeft);
Gizmos.color = tempColor
}

#endif

}

空白raycast target的可以在Gizmo里画,但是Image本身的不是那么好画,因为无法直接覆写原本的Editor。
一个笨办法就是做一个自己的Iamge然后也在Gizmo里画。
但其实这个是Graphic的property 不知道怎么做通用解决方案。