2017-09-28 154 views
0

如何在類中創建字符串數組?如何在Unity C中添加或追加數組中的值#

此外我必須添加或附加值到該數組。

我可以使用Firebase實時數據庫將數組值存儲在數據庫中。

不是特定的鍵。

我聲明數組爲:

private string[] uiddata; 

該數組在useed for循環和數組作爲

public void Click() 
{ 
    _uid = int.Parse(_uidText.text); 

    for(int i = 0; i < uiddata.Length;i++) 
    { 
     uiddata.Add(_uid); 

     //_score = int.Parse(_scoreText.text); 

     _uidRef.SetValueAsync(_uid); 
     //_scoreRef.SetValueAsync(_score); 

     _uidRef.RunTransaction(data => 
     { 
      data.Value =_uid ; 
      return TransactionResult.Success(data); 
     }).ContinueWith(task => 
     { 
      if (task.Exception != null) 
       Debug.Log(task.Exception.ToString()); 
     }); 
    } 
} 

添加元素在上面的腳本我嘗試在增加自己的價值數組,但給出了這樣的錯誤:

error CS1061: Type string[] does not contain a definition for Add and no extension method Add of type string[] could be found. Are you missing an assembly reference?

回答

3

由於您使用C#,你應該檢查這一點:

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/

正是這一部分:

The number of dimensions and the length of each dimension are established when the array instance is created. These values can't be changed during the lifetime of the instance.

因此,這意味着,你可以在一開始定義尺寸,例如5,然後你就可以像後續的陣列中添加值:

String[] numbers = new String[5]; 
numbers[0] = "hello1"; 
numbers[1] = "hello2"; 
numbers[2] = "hello3"; 
numbers[3] = "hello4"; 
numbers[4] = "hello5"; 

String[] words = new String[] {"hello1", "hello2", "hello3", "hello4", "hello5" }; 

但是,如果你試圖將一個額外的元素添加到這個數組,你將有一個例外

numbers[5] = 111111; //Exception here 

但是如果你需要追加值,你可以使用collections代替陣列。例如,一個列表:

List<String> myList = new List<String>(); 
myList.Add("Value1"); 
myList.Add("Value2"); 
... 
+0

但我怎樣才能在陣列中的統一附加價值 – shivani

+2

你不能,Unity引擎使用其他編程語言,我在你的情況下,看看它是C#,和我解釋你這不可能。你需要使用列表。嘗試使用ArrayList,就像我在示例中所說的那樣,在那裏您可以使用方法.Add(「value」)在需要時添加元素。 –

+0

因此,檢查我的答案的最後一部分,並將uiddata聲明爲ArrayList,而不是數組 –