Ben Greene
Ben Greene

Reputation: 11

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?

Upvotes: 1

Views: 1100

Answers (1)

OmniOwl
OmniOwl

Reputation: 5709

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!

Upvotes: 1

Related Questions