Search Unity

question on activate a gameobject with Vive trigger

Discussion in 'VR' started by beilei_ren, Jul 26, 2019.

  1. beilei_ren

    beilei_ren

    Joined:
    Jul 15, 2019
    Posts:
    7
    Hi!

    I am trying to activate a game object by press the trigger on Vive controllers. Somehow the code doesn't work. Could anyone help me on this?

    Here is the screenshot of the code attached:
     

    Attached Files:

  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Instead of screen shots, just copy the code, and paste it here between Code tags.

    And in addition, don't just say "it doesn't work." Suppose I call up my mechanic and tell him, "My car doesn't work. What do you think is wrong with it?"

    So tell us what you attached this script to, what other objects you filled in for its properties, what happens when you run it (including what, if anything, appears in the Console), and how that differs from what you wanted.
     
  3. beilei_ren

    beilei_ren

    Joined:
    Jul 15, 2019
    Posts:
    7
    Sorry about that~ Console is saying:
    "NullReferenceException: Object reference not set to an instance of an object
    triggertest.Start () (at Assets/triggertest.cs:12)"

    And here is the code (hope I am doing it in a right way~):

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using Valve.VR;
    5.  
    6.  
    7. public class triggertest : MonoBehaviour {
    8.     public GameObject who;
    9.     private SteamVR_Controller.Device device;
    10.  
    11.     void Start () {
    12.         if (device.GetPressDown(SteamVR_Controller.ButtonMask.Trigger))
    13.         {
    14.             who.SetActive(true);
    15.         }
    16.     }
    17.     void Update (){  
    18.     }
    19. }
     
  4. beilei_ren

    beilei_ren

    Joined:
    Jul 15, 2019
    Posts:
    7
    And when I press the trigger in play mode (the object is deactivated in advance), just nothing happens.
    Thank you so much~.~
     
  5. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Well that Console error is the real clue. It means that something on line 12 is null. And the only object reference on line 12 is `device`.

    You're not assigning to device anywhere in this script. And since device is a private variable, nothing else can assign to it. So I agree with the Console; device is null. ;)

    You need to figure out how to get device a valid reference to the device you want to check.
     
  6. beilei_ren

    beilei_ren

    Joined:
    Jul 15, 2019
    Posts:
    7
    Thank you so much! Eventually I found the if statement doesn't even work with keyboard input. It seems my keyboard/mouse/controller input is disabled before I get to solve the "object reference" problem. So I solved this by bring in VRTK.

    Thank you anyways!~~~