gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:20:12 25 4
gpt4 key购买 nike

我已经知道如何从 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

关于c# - 在不同情况下从更新中仅调用一次函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31328716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com