如何在Unity C#中的数组中添加或附加值

0 c# unity-game-engine

如何在课堂上创建字符串数组?

此外,我必须向该数组添加或附加值。

我可以使用 Firebase 实时数据库将数组值存储在数据库中。

不是特定的键。

我将数组声明为:

private string[] uiddata;
Run Code Online (Sandbox Code Playgroud)

该数组用于 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());
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面的脚本中,我尝试将我的值添加到数组中,但出现此错误:

错误 CS1061:类型string[]不包含定义Add并且找不到Add类型的扩展方法string[]。您是否缺少程序集参考?

Ign*_*rre 5

由于您使用的是 C#,您应该检查一下:

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

正是这一部分:

维数和每个的长度是在创建数组实例时确定的。在实例的生命周期无法更改这些值。

所以这意味着你可以在开始时定义一个大小,例如 5,然后你可以像下面这样向数组添加值:

String[] numbers = new String[5];
numbers[0] = "hello1";
numbers[1] = "hello2";
numbers[2] = "hello3";
numbers[3] = "hello4";
numbers[4] = "hello5";
Run Code Online (Sandbox Code Playgroud)

或者

 String[] words = new String[] {"hello1", "hello2", "hello3", "hello4", "hello5" };
Run Code Online (Sandbox Code Playgroud)

但是如果你尝试向这个数组添加一个额外的元素,你将有一个例外

numbers[5] = 111111; //Exception here
Run Code Online (Sandbox Code Playgroud)

但是如果你需要附加值,你可以使用集合而不是数组。例如一个列表:

List<String> myList = new List<String>();
myList.Add("Value1");
myList.Add("Value2");
...
Run Code Online (Sandbox Code Playgroud)

  • 您不能,统一引擎使用其他编程语言,正如我在您的情况下看到的那样,它是 c#,正如我向您解释的那样,这是不可能的。您需要使用列表。尝试使用我在示例中所说的 ArrayList,在那里您可以使用 .Add("value") 方法在需要时添加元素。 (2认同)