Using PointerEventData returns error: "Unexpected symbol"

Using PointerEventData returns error: "Unexpected symbol"

我是 C# 的新手,决定暂时开始使用它,因为大多数 Unity 教程都专注于它,而且我从未将 JavaScript 用于网页以外的任何内容。

在我尝试使用 Vector2.MoveTowards 方法之前,大多数情况下一切正常:

    void OnMouseDown() {
    int weapCoolDown = 1;
    Instantiate(bullet_player);
    Vector2.MoveTowards(GameObject.Find("player-1"), Vector2 PointerEventData.position(), float p1BulletSpeed);
}

Errors reported by Unity console

我尝试删除 Vector2,然后它要求我添加 EventSystems,但它已经存在于 UnityEngine 中。我修复它然后它说它不存在?然后我修复了它,它只是给了我一堆我什至不知道如何删除的其他错误。

当我尝试使用标识符时,它会分配它但不允许我使用它并且它像往常一样显示意外符号。

Unity 手册没有提供足够的细节或示例来真正帮助我解决这个问题,是否缺少 class 或参考资料,或者我应该尝试使用替代方法?

您应该检查代码中的一些事项:

未使用正确的参数调用 Vector2.MoveTowards()GameObject.Find() 将 return 一个游戏对象,而不是 Vector2。如果你正在寻找玩家 1 的当前位置,你应该从玩家 1 的 transform.position.

构造一个 Vector2
Vector2 playerPosition = new Vector2();
playerPosition.x = GameObject.Find("player-1").transform.position.x;
playerPosition.y = GameObject.Find("player-1").transform.position.y;

PointerEventData requires a using directive for EventSystem 的任何使用。为了包含它,请将 using UnityEngine.EventSystem 与其余的使用指令一起添加。

PointerEventData.position() 之前的 Vector2 前缀无效。它不是显式类型转换,因为它不在括号中,但不需要类型转换,因为位置将 return a Vector2.

pointerEventData.position 是从对象引用中提取的 属性。但是,PointerEventData.position() 的实现不正确地将其用作静态方法。由于实际上不是静态方法,而是动态方法属性,所以会编译失败,绘制错误

要使 pointerEventData 存在,它需要源自检索 eventData 的事件。不幸的是,OnMouseDown() 不会这样做。但是,来自 IPointerClickHandler called OnPointerClick(PointerEventData pointerEventData) 的接口方法具有您需要的 pointerEventData。

重构您现有的代码,这更接近您正在寻找的功能。

// Add this "using" directive
using UnityEngine.EventSystems;

// Be sure to implement the interface of IPointerClickHandler
public class NameOfYourScript : MonoBehaviour, IPointerClickHandler {

    //
    // Additional Code in your class. . . .
    // 

    // Replace OnMouseDown() with this.
    public void OnPointerClick(PointerEventData pointerEventData) {
        Instantiate(bullet_player);

        Vector2 playerPosition = new Vector2();
        playerPosition.x = GameObject.Find("player-1").transform.position.x;
        playerPosition.y = GameObject.Find("player-1").transform.position.y;

        Vector2.MoveTowards(playerPosition, pointerEventData.position, p1BulletSpeed);
    }
}