问题在于
void CountCoin()
{
cointext.text = ": "+ coincount;
CountCoin();
}
您自己叫CountCoin()
!
如果您想重复更新,可以例如使用Invoke
void CountCoin()
{
cointext.text = ": "+ coincount;
// calls this method again after 1 second
Invoke(nameof(CountCoin),1f);
}
或直接InvokeRepeating
void Start()
{
// calls CountCoin every second,the first time after 1 second delay
InvokeRepeating(nameof(CountCoin),1f,1f);
}
为了每秒调用一次。
或者只是完全删除嵌套调用,然后在Update
中添加一个嵌套调用,以使其在每一帧都被调用
void Update()
{
CountCoin();
}
或者,这就是我想做的:将coincount
设为property并将相应的行为添加到设置器中:
private int _coincount;
public int coincount
{
get { return _coincount; }
set
{
_coincount = value;
cointext.text = ": "+ value;
}
}
因此,每次更改属性时,代码都会自动执行
顺便说一句Find
相当昂贵,应避免使用。我会将您的代码更改为
private PlayerMove playermove;
IEnumerator StartSpawningCoins ()
{
// as long as you yield inside this is ok
while(true)
{
// only do find if needed
if(!player) player = GameObject.Find("PlayerMove");
// this should probably actually be done in the prefab not via code
coin.GetComponent<Renderer>().enabled = true;
yield return new WaitForSeconds(Random.Range(6f,16f));
GameObject k = Instantiate(coin);
playermove.coincount++;
float x = Random.Range(min_X,max_X);
k.transform.position = new Vector2(x,transform.position.y);
}
}
本文链接:https://www.f2er.com/3110559.html