按钮未调用OnPointerDown()方法

时间:2019-06-19 16:39:32

标签: c# unity3d

因此,我决定通过将台式机上的《吃豆人》游戏tutorial修改为Android游戏来学习Unity。现在,我试图将输入键从箭头键替换为sprite脚本中的UI按钮。然后将按钮拖动到“精灵”输入字段。 here is the input field image on my sprite

按下按钮时应该执行以下代码。但是,该按钮似乎没有触发任何方法。

if (rightButton.IsInvoking("OnPointerDown")){
                Debug.Log("OnPOinterDOwn() method is called");

这是我的精灵的完整代码:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class PacmanMove : MonoBehaviour {

    public float speed = 0.4f;
    Vector2 dest = Vector2.zero;

    public Button rightButton;
    public Button leftButton;
    public Button upButton;
    public Button downButton;

    // Use this for initialization
    void Start () {
        dest = transform.position;
    }

     //Update is called in fixed time interval
    void FixedUpdate() {
        //Move closer to Desstination
        Vector2 p = Vector2.MoveTowards(transform.position, dest, speed);
        GetComponent<Rigidbody2D>().MovePosition(p);

        //Check for input if not moving
        if ((Vector2)transform.position == dest) {
            if (Input.GetKey(KeyCode.UpArrow) && valid(Vector2.up))
                dest = (Vector2)transform.position + Vector2.up;
            if (Input.GetKey(KeyCode.RightArrow) && valid(Vector2.right))
                dest = (Vector2)transform.position + Vector2.right;
            if (Input.GetKey(KeyCode.DownArrow) && valid(-Vector2.up))
                dest = (Vector2)transform.position - Vector2.up;
            if (Input.GetKey(KeyCode.LeftArrow) && valid(-Vector2.right))
                dest = (Vector2)transform.position - Vector2.right;

            //Bellow code supposed to be trigger when my UI button is pressed
            if (rightButton.IsInvoking("OnPointerDown")){
                Debug.Log("OnPointerMethod() is called");
            }
        }

        // Animation Parameters
        Vector2 dir = dest - (Vector2)transform.position;
        GetComponent<Animator>().SetFloat("DirX", dir.x);
        GetComponent<Animator>().SetFloat("DirY", dir.y);
    }

    bool valid (Vector2 dir) {
        //Cast line from 'next to Pac-Man' to 'Pac-man'
        Vector2 pos = transform.position;
        RaycastHit2D hit = Physics2D.Linecast(pos + dir, pos);
        return (hit.collider == GetComponent<Collider2D>());
    }
}

有人可以启发我我想念什么吗?

1 个答案:

答案 0 :(得分:0)

完成更多教程后,我已经解决了这个问题。事实证明,我必须在按钮上调用事件触发器。 我还编写了一个附加到按钮的脚本,该脚本将从事件触发器中调用,并在子画面上设置布尔输入。

我将详细介绍my medium post