在不同情况下从更新调用一次函数

时间:2015-07-09 21:39:58

标签: c# unity3d

我已经知道如何从void Update(){ if(x == "blah" && once == true) { //call a function here once = false; } }

调用一次函数
//In the update method :

if (health <= StartHealth * 0.75)
{
    Escape();
}
// in the function being called :

else if(health<= StartHealth * 0.75f && health > StartHealth * 0.5f)
{
    for(int i = 0; i<2; i++)
    {
        GameObject x = Instantiate(clone, clonePointz[i].position, Quaternion.identity) as GameObject;
    }
}

else if(health <= StartHealth * 0.5f && health > StartHealth * 0.25f)
{
    for (int i = 0; i < 4; i++)
    {
        GameObject x = Instantiate(clone, clonePointz[Random.Range(0, 2)].position, Quaternion.identity) as GameObject;
    }
}

else if(health<= 0.25f * StartHealth)
{
    for (int i = 0; i < 6; i++)
    {
        GameObject x = Instantiate(clone, clonePointz[Random.Range(0, 2)].position, Quaternion.identity) as GameObject;
    }
}

但我怎么能多次这样做?

我有一个敌人(老板),我想在他的健康水平达到0.75,0.5,0.25(但每次只有一次)时调用一种方法。

这是我的代码BTW:

ActionEvent#getSource()

2 个答案:

答案 0 :(得分:2)

如果你想多次这样做并知道多少次,为什么不使用一个简单的计数器变量呢?

//Have counter initialized to some pre-defined start value
void Update()
{
    if(x == "blah" && counter > 0)
    {
        //call a function here
        counter--;
    }
}  

如果我误解了某些内容,请告诉我,我很乐意尝试重新调整我的答案。

答案 1 :(得分:2)

我现在手头没有Unity,但是这里有一个小C#程序应该按照你想要的方式运行并模拟引擎的Update调用。

它会记住最后一次调用Update时的健康值,并且只有在老板的健康值超过两个Update次呼叫之间的阈值之一时才会行动(即产生一些仆从)。

void Main()
{
    var boss = new BossBehaviour();
    boss.Damage(0.1f);
    boss.Update();
    boss.Damage(0.3f);
    boss.Update();
    boss.Damage(0.15f);
    boss.Update();
    boss.Update();
    boss.Damage(0.4f);
    boss.Update();
}

class BossBehaviour {

    float _currentHealth = 1.0f;
    float _healthFromLastUpdate = 1.0f;

    public void Update(){
        Console.WriteLine("Updating. Current health: {0}", _currentHealth);

        if (WasThresholdPassed(0.75f)){
            SpawnMinions();
        }

        if (WasThresholdPassed(0.5f)) {
            SpawnMinions();
        }

        if (WasThresholdPassed(0.25f)) {
            SpawnMinions();
        }

        _healthFromLastUpdate = _currentHealth;
    }

    bool WasThresholdPassed(float threshold) {
        if (_healthFromLastUpdate < threshold) 
            return false;
        if (_currentHealth < threshold)
            return true;
        return false;
    }

    void SpawnMinions() {
        /* ... */
        Console.WriteLine("> Spawning minions. Current health: {0}", _currentHealth);
    }

    public void Damage(float percentDamage) {
        _currentHealth -= percentDamage;
    }

}

这是它的输出:

Updating. Current health: 0,9
Updating. Current health: 0,6
> Spawning minions. Current health: 0,6
Updating. Current health: 0,45
> Spawning minions. Current health: 0,45
Updating. Current health: 0,45
Updating. Current health: 0,04999995
> Spawning minions. Current health: 0,04999995