2017-03-02 178 views
1

我使用Gear VR创建项目,您可以在其中旋转对象并根据耳机侧面的轻扫和轻触控制旋转对象并显示信息。Unity3D - Gear VR输入在场景之间不起作用

一切正常,我可以旋转和选择的东西,当我在Gear VR的侧面使用触摸板,但是当我改变场景并返回到主菜单,然后回到场景中,我只是在,功能停止工作。

我使用这个脚本我做:

using UnityEngine; 
using UnityEngine.SceneManagement; 
using System.Collections; 
using System; 

public class GearVRTouchpad : MonoBehaviour 
{ 
    public GameObject heart; 

    public float speed; 

    Rigidbody heartRb; 

    void Start() 
    { 
     OVRTouchpad.Create(); 
     OVRTouchpad.TouchHandler += Touchpad; 

     heartRb = heart.GetComponent<Rigidbody>(); 
    } 

    void Update() 
    { 
     if (Input.GetKeyDown(KeyCode.W)) 
     { 
      SceneManager.LoadScene("Main Menu"); 
     } 
    } 


    void Touchpad(object sender, EventArgs e) 
    { 
     var touches = (OVRTouchpad.TouchArgs)e; 

     switch (touches.TouchType) 
     { 
      case OVRTouchpad.TouchEvent.SingleTap:     
       // Do some stuff  
       break;  

      case OVRTouchpad.TouchEvent.Up: 
       // Do some stuff 
       break; 
       //etc for other directions 

     } 
    } 
} 

我注意到,当我开始我的游戏,创建一个OVRTouchpadHelper。我不知道这与我的问题有什么关系。

我得到的错误是:

MissingReferenceException: The object of type 'GearVRTouchpad' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.

我还没有提到这个脚本其他地方。

当我在播放模式下检查场景时,脚本仍然存在,变量赋值仍然存在。

任何帮助将是伟大的!

+0

您的错误不在GearVRTouchpad类中,它的类内使用GearVRTouchpad。如果你能提供那些抛出这个异常的东西会很好。 –

+0

我认为可能是这种情况,但我没有在其他脚本或文件中使用这个脚本? – Tom

回答

2

OVRTouchpad.TouchHandler是一个static EventHandler(所以它会一直持续到游戏的一生)。您的脚本在创建时订阅它,但在销毁时不会取消订阅。当您重新加载场景时,旧的订阅仍然存在,但旧的GearVRTouchpad实例已消失。这将导致下次TouchHandler事件触发时MissingReferenceException。添加到您的类:

void OnDestroy() { 
    OVRTouchpad.TouchHandler -= Touchpad; 
} 

现在,每当与GearVRTouchpad行为GameObject被破坏,static事件OVRTouchpad将不再有对它的引用。

+1

辉煌,完美的作品。谢谢! – Tom

+0

@Tom乐意帮忙! – Foggzie