【问题标题】:Variable value not updating in string变量值未在字符串中更新
【发布时间】:2016-11-18 04:06:02
【问题描述】:

我有一个名为“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 关键字粘贴到字符串上,但没有成功。有任何想法吗?谢谢。

【问题讨论】:

  • 你在哪里设置 Manager.playerName 的值?
  • 在 IEnumerator 中。值更新良好,如 Debug.Log 语句所示,关于该值以及其他文本字段的更新良好。只是这个字符串以某种方式没有正确的值。可能是因为它是静态的,或者我该如何强制刷新或其他什么?

标签: c# unity3d


【解决方案1】:

这是由于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();
    }
}

【讨论】:

  • 很有趣,谢谢。不幸的是,没有更简单的方法来强制刷新,但是哦。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-24
  • 1970-01-01
  • 2015-04-02
  • 1970-01-01
  • 2019-11-29
相关资源
最近更新 更多