我有一个名为“DialogueLines.cs”的类,其中有一个公共静态字符串列表。问题是当我访问这个特定字符串时:
public static volatile string cutscene_introHurt7 = "* " + Manager.playerName + " huh?\n That's a nice name.";
Manager.playerName
的值不正确。在开始时,playerName的值设置为“Garrett”。当更新为其他内容时,例如“Zip”,对话仍然会说:
* Garrett, huh? That's a nice name.
我还检查了Debug.Log()语句,以确保名称正确更改。我认为这是因为字符串没有使用正确的变量值进行更新。正如您所看到的,我已经尝试将volatile关键字粘贴到字符串上而没有运气。有任何想法吗?感谢。
答案 0 :(得分:3)
这是由于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();
}
}