简体   繁体   中英

How to script a Button press in C#, to trigger another event?

I'm working on Unity, w/ Vuforia.

I've got Virtual buttons that I need to act like the Up/Down Arrows on the keyboard to move an object which is not in its image target, so I'm searching for the basics.

My class starts like this:

public void OnButtonPressed(VirtualButtonAbstractBehaviour vb){
...
}

What do I need to put in this to make it act like the up button?

Without these virtual buttons, my script would move the object like this:

void FixedUpdate(){
        float moveHortizonal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Vector3 movement = new Vector3 (moveHortizonal, 0, moveVertical);

        rigidbody.AddForce (movement * speed);
    }

Figured out how to do it, and here's a small tutorial on my findings

First of all, you start with registering the buttons:

void Start () {
        VirtualButtonBehaviour[] vbs = transform.GetComponentsInChildren<VirtualButtonBehaviour> ();

        for (int i=0; i < vbs.Length; ++i) {
            vbs[i].RegisterEventHandler(this);
        }

And now you go ahead and start with the function of the button

   public void OnButtonPressed(VirtualButtonAbstractBehaviour vb){
    //specify which button you want to function by using the if statement
    if(vb.name=="ButtonName") { callButtonfunction();}
    }

Similarly if you want a button to do something on release:

   public void OnButtonReleased(VirtualButtonAbstractBehaviour vb){
    //specify which button you want to function by using the if statement
    if(vb.name=="ButtonName") { callButtonfunction();}
    }

In case you want your button to control a Gameobject, then go ahead and declare the GameObject as a public variable in the class so that it can be accessed in the Inspector and assigned accordingly.

public GameObject human;

Where GameObject is the variable type and human is the variable name that we use for reference

It's as simple as that.

The Vuforia logs are very badly documented and so you can almost never get an answer from there, so I 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