This question has already been answered:

I am studying C # and Unity, the question arose.

Suppose we create an empty array with a fixed volume. Then assign the value to the array element.
Question: Why is the assignment incorrect to do outside the Start method?

That is why it is so correct:

using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChaikaLetit : MonoBehaviour { string[] names = new string[5]; // Use this for initialization void Start () { names [0] = "Jessie"; print ("First name is "+names[0]); } } 

And so no:

 using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChaikaLetit : MonoBehaviour { string[] names = new string[5]; names [0] = "Jessie"; // Use this for initialization void Start () { print ("First name is "+names[0]); } } 

Thanks a lot in advance!

Reported as a duplicate by Grundy participants, Alexey Shimansky , Community Spirit Jan 27 '17 at 10:08 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • 2
    because this is a C # syntax error. You can use fields only inside property or constructor methods. By the way, there was already a similar question, you need to search - Grundy
  • 2
    The question does not apply to Unity. Therefore, I would recommend you to start exploring C # - Aleksey Shimansky
  • @Grundy But at the same time, if we set the values ​​of the elements immediately during the creation of the array string[] names = new string[]{"Jessie"}; this is not considered to be “using” an already created field, so correctly, right? - Rumata
  • @Rumata, yes, this is all part of field initialization - Grundy
  • @ Alexey Shimansky Was not sure if this is related to how Unity interprets C #. - Rumata

1 answer 1

In C #, you can't do this, but you can:

 using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChaikaLetit : MonoBehaviour { string[] names = new string[5] { "Jessie", "name 2 ", "name 3", "name 4", "name 5" }; // Use this for initialization void Start () { print ("First name is "+names[0]); } } 

https://msdn.microsoft.com/uk-ua/library/0a7fscd0.aspx

I will explain not scientifically, but in a simple way: outside of functions in C #, you can only declare and initialize variables, while names [0] = "Jessie"; This is a reference to the element of the array.


But if we consider Unity, then constructors are not recommended in it, so an array of Unity types will have to be initialized either in the editor or in the Awake / Start function, otherwise Unity may generate an error / warning.