0

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.

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

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. Are you missing an assembly reference?

1 Answer 1

7

Since you are using C#, you should check this:

https://learn.microsoft.com/en-us/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:

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");
...
Sign up to request clarification or add additional context in comments.

2 Comments

You can not, the unity engine use other programming language, as I see in your case it is c#, and as I explained you it is not possible. You need to use list. Try to use ArrayList as I say in the example, and there you can use the method .Add("value") to add elements when you need.
So check the last part of my answer, and declare uiddata as an ArrayList, not as an Array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.