Skip to main content
 首页 » 编程设计

c#之在不同情况下从更新中仅调用一次函数

2024年02月06日12zhoujg

我已经知道如何从 Update() 中只调用一次函数

void Update(){ 
    if(x == "blah" && once == true) 
    { 
        //call a function here 
       once = false; 
    } 
} 

但是我怎样才能多次这样做呢?

我有一个敌人(boss),我想在他的生命值达到 0.75、0.5、0.25 时调用一个方法(但每次只能调用一次)。

顺便说一句,这是我的代码:

//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; 
    } 
} 

请您参考如下方法:

我现在手边没有 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