简体   繁体   English

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

[英]How to add or append value in array in Unity C#

How can I create a string array in class? 如何在课堂上创建字符串数组?

Also I have to add or append values to that array. 另外,我必须向该数组添加或附加值。

I can use Firebase real-time database to store array values in database. 我可以使用Firebase实时数据库在数据库中存储数组值。

Not to a specific key. 没有特定的密钥。

I declared array as: 我声明数组为:

private string[] uiddata;

That array is useed in a for loop and add elements to the array as 该数组在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());
        });
    }
}

In the script above I try to add my value in the array but gives this error: 在上面的脚本中,我尝试将值添加到数组中,但出现此错误:

error CS1061: Type string[] does not contain a definition for Add and no extension method Add of type string[] could be found. 错误CS1061:类型string[]不包含定义Add并没有扩展方法Add类型的string[]可以找到。 Are you missing an assembly reference? 您是否缺少装配参考?

Since you are using C#, you should check this: 由于您使用的是C#,因此应检查以下内容:

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

Exactly this part: 正是这一部分:

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. 这些值在实例的生存期内无法更改

So it means you can define a size at the beginning, for example 5, and then you can add values to the array like follow: 因此,这意味着您可以在开头定义一个大小,例如5,然后可以将值添加到数组,如下所示:

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

or 要么

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

But if you try to add an extra element to this array you will have an exception 但是,如果您尝试向此数组添加额外的元素,则会出现异常

numbers[5] = 111111; //Exception here

But if you need append values, you can use collections instead of arrays. 但是,如果需要附加值,则可以使用集合而不是数组。 For example a List: 例如一个列表:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM