Physics2D.Raycast 返回 null

Loc*_*erd 2 c# unity-game-engine

我有一个问题让我在这里非常难倒。我将从关键代码到鼠标输入 - 然后它后来成为触摸输入,但首先我想弄清楚为什么我不能只用鼠标来做到这一点。

我有一个 raycast2d 设置 - 我希望 raycast 读取与屏幕上我的对象的碰撞。只有当它是一个标记为“猫”的物体时,它们才会做出反应——基本上一旦发生这种情况,猫就会冲出去并试图攻击。但是,它告诉我标签本身是一个实例化的引用。但是对象本身默认存在,所以我不确定在这里做什么。这是我的整个脚本。

 void Update() {
    //if ((Input.GetKeyDown(KeyCode.O) && !attacking && attackTimer <= 0)) {
    if (Input.GetMouseButtonDown(0) && !attacking && attackTimer <= 0) {  //every frame check to see if the mouse has been clicked.
                                                                          //Get the mouse position on the screen and send a raycast into the game world from that position.
        Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);//Vector 2 means only 2 points of axis are read. worldpoint means check the point of the world. Camera is used to determien what we are looking at, and we fill it with our mouse location.
        RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero);
        if (hit.collider == null) {//THIS IS THE LINE that says it is having issues. If i REMOVE this line, ANYWHERE i click on the screen activates the cat and thats not what I want to happen.

            Debug.Log("No Object Touched");

            if (hit.collider.CompareTag("Cat")) {
                GameManager.Instance.AudioSource.PlayOneShot(SoundManager.Instance.Swipe);

                attacking = true;
                attackTimer = attackCd;

                attackTrigger.enabled = true;
            }
Run Code Online (Sandbox Code Playgroud)

更新代码以匹配请求的更改:我现在得到的错误是 NullreferenceException - 对于:

 if (hit.collider.CompareTag("Cat")) {
Run Code Online (Sandbox Code Playgroud)

这与我之前遇到的错误相同,在使用程序员推荐的方法重新测试后。

控制台会告诉我,我没有点击一个对象,然后给我显示空值。所以我想它试图告诉我它没有找到任何存在于场景中的标记为 cat 的东西?尽管 Cat 是添加的自定义标签,并且它已应用于作为猫的游戏对象 - 带有 Box 碰撞器。它是否需要材料或任何东西来阅读它是否存在?有没有另一种方法可以通过点击它的特定位置来调用这个对象?

更新:

       Debug.Log("No Object Touched");
                if (hit.collider) {
                    if (hit.collider.tag == "cat1") { - 
Run Code Online (Sandbox Code Playgroud)

这摆脱了空引用,但它根本不读取猫。如果我点击猫没有任何反应。是的,它现在在编辑器中正确标记为“cat1”。meanign 标签 - 新的自定义标签,创建了 cat1 标签。转到游戏对象,将标签更改为 cat1。还确保一个 colider 是开启的,并且是触发器。

Ash*_*win 5

经过几个小时的搜索,我终于找到了为空的原因。

您需要将“New Component”>“Physics”>“Box Collider”附加到您的精灵游戏对象。

现在,您可以在添加到游戏对象的脚本中使用以下代码片段来了解是否单击了对象:

private Ray ray;
private RaycastHit hit;

private void Update()
{
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) 
    {
        ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);

        if (Physics.Raycast(ray, out hit, Mathf.Infinity))
        {
            if (hit.transform.gameObject.name == "YourGameObject")
            {
                // Do your stuff on click
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是为什么 3d 对象可以轻松检测到触摸的原因,因为在您创建它们时,它们已经附加了碰撞器。

希望这个答案对某人有所帮助。