字符串中的变量值未更新

本文关键字:更新 变量值 字符串 | 更新日期: 2023-09-27 18:18:27

我有一个名为"DialogueLines.cs"的类,其中我有一个公共静态字符串的列表。问题是当我访问这个特定的字符串时:

public static volatile string cutscene_introHurt7 = "* " + Manager.playerName + " huh?'n  That's a nice name.";

Manager.playerName的值不正确。一开始,玩家名称的值设置为"加勒特"。当更新为其他内容(例如"Zip"(时,对话框仍会显示: * Garrett, huh? That's a nice name. 我还检查了 Debug.Log(( 语句以确保名称正确更改。我认为这是因为字符串没有使用正确的变量值进行更新。如您所见,我已经尝试将 volatile 关键字粘贴到字符串上,但没有运气。有什么想法吗?谢谢。

字符串中的变量值未更新

这是

由于static的行为。静态将预编译字符串,这意味着即使您更改用户名,预编译的字符串也不会更改。

但是,您可以简单地更改字符串。在使用它之前再次执行整个作业

cutscene_introHurt7 = "* " + Manager.playerName + " huh?'n  That's a nice name.";

但是,如果可能的话,您可能需要考虑将其设置为非静态。之后,您的预期行为将起作用。

在示例控制台应用程序下方查看静态解决方案的运行情况

using System;
class Program
{
    public static string playerName = "GARRET";
    // This will be concatonated to 1 string on runtime "* GARRET huh? 'm That's a nice name."
    public static volatile string cutscene_introHurt7 = "* " + playerName + " huh?'n  That's a nice name.";
    static void Main(string[] args)
    {
        // We write the intended string
        Console.WriteLine(cutscene_introHurt7);
        // We change the name, but the string is still compiled
        playerName = "Hello world!";
        // Will give the same result as before
        Console.WriteLine(cutscene_introHurt7);
        // Now we overwrite the whole static variable
        cutscene_introHurt7 = "* " + playerName + " huh?'n  That's a nice name.";
        // And you do have the expected result
        Console.WriteLine(cutscene_introHurt7);
        Console.ReadLine();
    }
}