2016-11-18 30 views
1

我有一個名爲「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()語句來檢查名稱是否正確更改。我認爲這是因爲字符串沒有用正確的變量值進行更新。正如你所看到的,我已經試着將揮發性關鍵字粘貼到字符串上,但沒有運氣。有任何想法嗎?謝謝。

+0

靜態解決你在哪裏設置Manager.playerName價值? – A3006

+0

在IEnumerator中。該值更新正確,如Debug.Log語句所顯示的有關值以及其他正在更新的文本字段正常。這只是一個字符串,它沒有正確的值。難道是因爲它是靜態的,或者我該如何強制刷新或者事端'? – GMR516

回答

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(); 
    } 
} 
+0

有趣,謝謝。這是不幸的,有沒有更簡單的方法來強制刷新,但哦。 – GMR516