首页 文章

在Update()之外创建的变量

提问于
浏览
1

让我们想象一下,我有一个移动的生物:

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不同 .
所以我想知道如何用更定性的代码实现相同的结果?

1 回答

  • 2

    将布尔 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类中 .

相关问题