如何在Unity中显示收集的硬币数量而不会溢出(访问另一个脚本)?

我有两个脚本。 PlayerMove.cs Spawner.cs 。 在PlayerMove.cs中,我需要一个将文本更改为硬币数量的功能。

>>> def f(a,b,*,c=1,):pass
  File "<stdin>",line 1
    def f(a,):pass
                       ^
SyntaxError: invalid syntax

在Spawner.cs中,我生成硬币,并且每次生成时都希望增加coincount(这是PlayerMove.cs的公共变量)。

*

当我使用这些时,我会得到堆栈溢出错误。我该如何解决?

shilitao0624 回答:如何在Unity中显示收集的硬币数量而不会溢出(访问另一个脚本)?

问题在于

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

大家都在问