随着时间的推移,破坏了我的帧率,unity c#
本文关键字:我的 坏了 帧率 unity 时间 | 更新日期: 2023-09-27 18:16:33
大家好。我对编写脚本很陌生,我是通过制作游戏来学习的。我试图给玩家施加一种随时间变化的伤害效果。虽然我有一些工作,当计时器上升,我的帧率从60下降到10以下。所以我希望有人能帮助解释为什么这是,如果我的方法是可行的,有什么更好的我能做的。这是我的代码。
public class AllDamage : MonoBehaviour
{
//Type of Damage to be applied when attatched to a game object
public bool isFire;
public bool isIce;
public bool isElectric;
public bool isWind;
public bool isBlunt;
public bool isSharp;
public bool isToxic;
public bool isPoisen;
public bool isTicking; // is this damage over time
public int ticks = 0;
public int DotDuration;
// Ammount or initial damage
public float ammountHealthDmg = 10f;
public float ammountPhysicalDmg = 10f;
public float ammountMentalDmg = 10f;
// ammount of damage over time
public float tickHealthDmg = 1f;
public float tickPhysicalDmg = 1f;
public float tickMentalDmg = 1f;
void Update()
{
if(isTicking == true)
{
applyDoT ();
StartCoroutine("CountSeconds");
}
}
IEnumerator CountSeconds()
{
int DoTDuration = 0;
while(true)
{
for (float timer = 0; timer < 1; timer += Time.deltaTime)
yield return 0;
DoTDuration++;
Debug.Log(DoTDuration + " seconds have passed since the Coroutine started.");
if(DoTDuration == 10)
{
StopCoroutine("CountSeconds");
isTicking = false;
}
}
}
void applyDoT()
{
// ticks increments 60 times per second, as an example
ticks++;
// Condition is true once every second
if(ticks % 60 == 0)
{
decrementStats(tickHealthDmg, tickPhysicalDmg, tickMentalDmg);
}
}
// is this the player?... what am i?...apply my inital damage...do i have damage over time
void OnTriggerEnter(Collider other)
{
if(other.tag == "Player")
{
if(isFire)
{
decrementStats(ammountHealthDmg, ammountPhysicalDmg, ammountMentalDmg);
isTicking = true;
}
if(isIce)
{
decrementStats(ammountHealthDmg, ammountPhysicalDmg, ammountMentalDmg);
isTicking = true;
}
if(isElectric)
{
decrementStats(ammountHealthDmg, ammountPhysicalDmg, ammountMentalDmg);
}
if(isWind)
{
decrementStats(ammountHealthDmg, ammountPhysicalDmg, ammountMentalDmg);
}
if(isBlunt)
{
decrementStats(ammountHealthDmg, ammountPhysicalDmg, ammountMentalDmg);
}
if(isSharp)
{
decrementStats(ammountHealthDmg, ammountPhysicalDmg, ammountMentalDmg);
isTicking = true;
}
if(isToxic)
{
decrementStats(ammountHealthDmg, ammountPhysicalDmg, ammountMentalDmg);
isTicking = true;
}
if(isPoisen)
{
decrementStats(ammountHealthDmg, ammountPhysicalDmg, ammountMentalDmg);
isTicking = true;
}
}
}
// - stat values
void decrementStats(float health, float physical, float mental)
{
Stats.health -= health;
Stats.physical -= physical;
Stats.mental -= mental;
Stats.CheckAllStats();
}
}
你通过在Update()
回调中调用StartCoroutine()
来多次启动协同程序,每帧一次。您应该做的是,当您想启动协程时,将shouldStartTicking
(在代码中称为isTicking
)标志设置为true
,然后在协程中立即将其设置为false
。但更简洁的解决方案是直接从记录命中的代码开始协程。我还建议您从协程调用decrementStats
方法,而不是使用外部反变量来传达DoT效果的状态。