Unity点击获取UGUI的UI物体的方法

打算做一个动态加载并且给button赋值的功能,但是卡在了获取UI名字上面,找了很多资料,都不是很实用,不过,皇天不负有心人,方法被我找到了,毕竟不是大神,什么都能自己写。。。。。。

这里面要感谢“X哥”提供的方法,名字我就不写全了。

点击UI获取UI物体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public GameObject OnePointColloderObject()
{
PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
eventDataCurrentPosition.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
if (results.Count > 0)
{
return results[0].gameObject;
}
else
{
return null;
}
}

方法的使用

1
GameObject go = OnePointColloderObject();

如果想要讨论更多unity相关的知识欢迎进群:482349226,等待你的加入!!!