首页 > 解决方案 > 按钮不调用 OnPointerDown() 方法

问题描述

所以我决定通过将桌面上的 Pacman 游戏教程修改为 Android 游戏来学习 Unity。现在,我尝试将精灵脚本上的输入键从箭头键替换为 UI 按钮。然后将按钮拖动到精灵输入字段。 这是我的精灵上的输入字段图像

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

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

有人能告诉我我错过了什么吗?

标签: c#unity3d

解决方案


在做了更多教程之后,我已经解决了这个问题。结果我必须在我的按钮上调用事件触发器。我还编写了另一个附加到按钮的脚本,它将从事件触发器中调用,并在精灵上设置布尔输入。

我在我的中等帖子上详细说明。


推荐阅读