首页 > 解决方案 > 一个变量是空的,即使我已经设置了它

问题描述

我试图让我的敌人移动使用 A* Pathfinding 项目(按照 Brackeys 的教程,可以在这里找到)。

在我的Start()方法中,我使用InvokeRepeating("GeneratePath", 0f, .5f);

void GeneratePath()
    {
        if (seeker.IsDone())
            seeker.StartPath(rb.position, Game.currentPlayer.GetComponent<Rigidbody2D>().position, OnPathComplete);
    }

然后:

void OnPathComplete(Path p)
    {
        if (!p.error)
        {
            path = p;
            currentWayPoint = 0;
        }
    }

请注意,我的path变量已设置。

在我的Update()方法中:

public void MoveAI()
    {
        if (Game.currentPlayer == null || path == null) return;

        if (currentWayPoint >= path.vectorPath.Count)
        {
            reachEndOfPath = true;
            return;
        }
        else
        {
            reachEndOfPath = false;
        }

        Vector2 dir = ((Vector2)path.vectorPath[currentWayPoint] - rb.position).normalized;
        Vector2 force = dir * speed * Time.deltaTime;

        rb.AddForce(force);

        float distance = Vector2.Distance(transform.position, path.vectorPath[currentWayPoint]);

        if (distance < nextWaypointDistance)        
            currentWayPoint++;                    
    }

既然是我的Update()方法,我的敌人应该移动。但他们没有。

我设置了一个断点并确认它path确实为空。

怎么样?我已经设置好了。

编辑:我确实移动了这两个

path = p;
currentWayPoint = 0;

在 if 语句之外(查看问题是否存在p.error)并且path仍然为空。

标签: c#unity3d

解决方案


推荐阅读