在 Update() 之外创建的变量

Variables created outside the Update()

假设我有一个会移动的生物:

        bool pathFound = false;
        void Update()
        {
            if(!pathFound)
            {
                //Find a destination point
                pathFound = true;
            }

            //Move creature to point

            if(Creature reached the point)
            {
                pathFound = false;
            }
        }

因此移动取决于在函数外创建的变量。
如果我想添加完全相同的第二个生物,代码将被复制:

        bool pathFound1 = false;
        bool pathFound2 = false;
        void Update()
        {
            if(!pathFound1)
            {
                //Find a destination point 1
                pathFound1 = true;
            }
            //Move creature 1 to point 1
            if(Creature reached the point 1)
            {
                pathFound1 = false;
            }

            if(!pathFound2)
            {
                //Find a destination point 2
                pathFound2 = true;
            }
            //Move creature 2 to point 2
            if(Creature2 reached the point 2)
            {
                pathFound2 = false;
            }
        }

我觉得很奇怪而且效率低下。即使我将所有这些步骤移动到一个函数中,也应该创建两个几乎相同的函数,只有 pathFound1 和 pathFound2 不同。
所以我想知道如何使用更定性的代码获得相同的结果?

将布尔值 pathFound 作为 public 成员放入 Creature,默认值初始化为 false

那么你可以拥有:

void Update()
    {
        foreach (Creature creature in yourCreaturesList)
        {
            if (creature.PathFound)
            {
                //Find a destination point for creature
                creature.PathFound = true;
            }

            //Move creature to its target point
            if(creature reached the point)
            {
                creature.PathFound = false;
            }
        }
    }

如果需要,也将其他参数封装在 Creature 中 class。