简体   繁体   中英

Unity Steam VR how to reference the currently held object?

In my script attached to my controllers I want to be able to reference the child object that the controller is holding at the time, but I'm not sure how. Any idea how to do this, would I need to tag the objects or something along those lines?

One way to do it, which is something I've done before at least, is to use System events.

You make two events in your controllers:

event EventHandler OnPickedUp;
event EventHandler OnLetGo;

If you manage to get something within range of picking it up, you fire off the event OnPickekUp

public class MyVRController
{
    public event EventHandler OnPickedup;
    public event EventHandler OnLetGo;
    private bool HasObject = false;
    ...
    private void SuccessfullyPickedUp(GameObject pickedUpGO)
    {
        if(OnPickedUp != null)
        {
            HasObject = true;
            OnPickedUp(pickedUpGO, null);
        }
    }
    ...
    private void OnLetGo()
    {
        if(OnLetGo != null)
        {
            HasObject = false;
            OnLetGo(this, null);
        }
    }
    ...
}

Then whatever needs to care about the fact that you picked something up or you dropped something, can do this:

public class MyGameManager
{
    public void Start()
    {
        // However you reference the controllers, do it here.
        myRightVRController.OnPickedUp += SomeFunc1;
        myRightVRcontroller.OnLetGo += SomeFunc2;
        myLeftVRController.OnPickedUp += SomeFunc3;
        myLeftVRController.OnLetGo += SomeFunc4;
        // The rest of your initialization...
    }
}

If you want you can specify what controller the event came from in the EventArgs that can be passed (currently passing null ).

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM