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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-13 06:25:27

问题


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);
    }

回答1:


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.



来源:https://stackoverflow.com/questions/28977822/how-to-script-a-button-press-in-c-to-trigger-another-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!