【发布时间】:2015-02-24 05:08:10
【问题描述】:
Unity 刚刚在 4.6 版中实现了新的 ui 画布。它很棒,但我试图检测屏幕的坐标并检查画布 ui 对象是否在该像素中可见。所以要做到这一点,我尝试了很多方法来实现它,但只有两种方法接近。
if(EventSystems.EventSystem.current.IsPointerOverGameObject(touch.fingerId)){
shouldLatchFinger = 假; }
上述代码的问题在于它通过手指 id 进行搜索,这很好,但是当您松开手指时按下手指时,它将转到我拥有的函数,并且由于 touch.phase == end ispointerovergameobject 将返回false 尽管我的函数仍然需要返回 true,因为该位置实际上仍然位于画布 ui 对象上,您会认为它允许我输入坐标系,但似乎屏幕坐标没有过载
即:
void update()
{
switch (touch.touchphase)
{
case touchphase.began:
shouldLatchFinger = false;
if(EventSystems.EventSystem.current.IsPointerOverGameObject(touch.fingerId)){
shouldLatchFinger = false;
}
break;
case touchphase.ended:
shouldLatchFinger = false;
if(EventSystems.EventSystem.current.IsPointerOverGameObject(touch.fingerId)){
shouldLatchFinger = false;
}
break;
}
}
因此,尽管我希望使用该代码,但我还是选择了其他方法
工作 c# 实现
if(EventSystem.current != null){
PointerEventData pointer = new PointerEventData(EventSystem.current);
pointer.position = Camera.main.WorldToScreenPoint(hit.point);
List<RaycastResult> raycastResults = new List<RaycastResult>();
EventSystem.current.RaycastAll(pointer, raycastResults);
if(raycastResults.Count>0){
return;
}
}
此方法如我所愿完美运行,但我也需要在 JavaScript 中重新实现它,并且在我尝试这样做时,我发现他们的新 ui 上的统一 api 文档从 4.6 开始相当缺乏和不准确。 http://docs.unity3d.com/ScriptReference/EventSystems.EventSystem.RaycastAll.html 如果您在该页面上在 java 和 c# 之间切换,unity 显然是在说 list 类也存在于 javascript 中,我是否遗漏了什么或者有人可以帮我完成将其转换为 js。
我尝试转换为 JS
shouldLatchFinger = true;
if(EventSystems.EventSystem.current != null){
var pointer : EventSystems.PointerEventData = new EventSystems.PointerEventData (EventSystems.EventSystem.current);
pointer.position = touch.position;
var raycastResults ;// List(RaycastHit);// = new List(RaycastHit);
EventSystems.EventSystem.current.RaycastAll(pointer, raycastResults);
if(raycastResults != null){
shouldLatchFinger=false;
}
}
}
这会在 logcat 中给出错误,但是
NullReferenceException: Object reference not set to an instance of an object
I/Unity ( 4109): at UnityEngine.EventSystems.EventSystem.RaycastAll (UnityEngine.EventSystems.PointerEventData eventData, System.Collections.Generic.List`1 raycastResults) [0x00000] in C:\BuildAgent\work\XXXXXXXXXXXXX\Extensions\guisystem\guisystem\EventSystem\EventSystem.cs:158
I/Unity ( 4109): at xxxxx.Update () [0x000e6] in Z:\Documents\Projects\XXXXXXXXXX\Assets\Standard Assets\Scripts\xxxxx.js:159
I/Unity ( 4109):
I/Unity ( 4109): (Filename: C Line: 0)
如果我没记错的话是因为
" at UnityEngine.EventSystems.EventSystem.RaycastAll (PointerEventData eventData, System.Collections.Generic.List`1 raycastResults)"
如此处所示,引用 system.collections.generic.list 但这里的问题是我的 raycastresults 列表是一个 var 或对象,当 eventsystem.raycastall 尝试访问它时,它引用了一个空对象,因为它更有可能尝试访问 Add 方法以填充数组,但由于尚未初始化,因此无法访问。所以我想总体问题是如何在 javascript 中实例化一个列表以实现统一。
【问题讨论】:
-
我确信答案很简单,我只是太笨了,看不到它。
标签: android user-interface unity3d unityscript