我正在尝试通过引用更改变量。但是,变量仅更改一次

I am trying to change a variable through reference. However the variable changes only once

提问人:Alvaro 提问时间:10/11/2022 最后编辑:Soroush HosseinpourAlvaro 更新时间:10/14/2022 访问量:109

问:

//This variable I am trying to change
int levelCount = 0;

 IEnumerator LoadScene(float waitTime){
    yield return new WaitForSeconds(waitTime);
    LevelCount(ref levelCount); //through this method I am trying to increase the variable levelCount by one
}

//This function should achieve it but it doesn’t work
public void LevelCount(ref int thislevelCount){
    thislevelCount ++;
}

我正在尝试通过 LevelCount(ref int lvlCount) 方法更改变量 levelCount。

C# Unity-Game-Engine 按引用传递

评论

0赞 Elec1 10/11/2022
尝试将 'thislevelCount ++;' 替换为 'thislevelCount += 1';
0赞 gunr2171 10/11/2022
@Elec1这完全是一回事 dotnetfiddle.net/G3lHYU

答:

0赞 Skylar Stickley 10/12/2022 #1

您不需要将变量作为参考进行寻址。只需将其保留为公共 void LevelCount(int thislevelCount)。

或者,如果您不打算扩展 LevelCount 方法,则可以简化代码。

 IEnumerator LoadScene(float waitTime){
    yield return new WaitForSeconds(waitTime);
    SceneManager.LoadScene(levels[levelCount]);
    levelCount+=1;
}

评论

0赞 Alvaro 10/13/2022
我确实尝试将 levelCount ++;但在 LoadScene 方法中,它仅在调用该方法时才增加 1,然后返回到 0。但是我会尝试 LevelCount(int thislevelCount);
0赞 Alvaro 10/13/2022
所以它不知何故对我不起作用。将其包含在 IEnumerator 方法中
0赞 Skylar Stickley 10/13/2022
我想我知道你的问题,知道它在使用时会恢复为 0。每当加载新场景时,都会在对象之间重置变量。所以 levelCount 回到 0。尝试将其设置为静态变量(public static int levelCount;)。或者,使用单例 videlais.com/2021/02/20/...
1赞 Alvaro 10/15/2022
是的,谢谢公共静态 int 解决了它!该变量在每次场景加载时都会重置。让我检查一下如何将您的评论标记为“已解决”答案。