[Bug] Array will not work until set to private.

Create a new project,
First run this:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
 
    public class HelloWorld : MonoBehaviour {
 
        public string[] names = new string[5];
 
        // Use this for initialization
        void Start () {
  
        }
 
        // Update is called once per frame
        void Update () {
   
        }
    }

Then run this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour {

    public string[] names = new string[]{"Jesse", "Freeman"};

    // Use this for initialization
    void Start () {
 
        print (names[0] + " " + names[1]);
        print ("Total Names " + names.Length);
    }
 
    // Update is called once per frame
    void Update () {
 
    }
}

you will notice that the second script does not work.

This will work:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour {

    string[] names = new string[]{"Jesse", "Freeman"};

    // Use this for initialization
    void Start () {

        print (names[0] + " " + names[1]);
        print ("Total Names " + names.Length);
    }

    // Update is called once per frame
    void Update () {

    }
}

please give error message

If its already public, then you have to change it from the inspector.

1 Like

This. It’s not a bug, it’s a feature. Unity overrides default values via the inspector.

If you want to override the inspector values use Start or Awake.

Actually it doesn’t. If you change the int to initialise as 4 in the script, the value in the inspector and console will stay at 2.

Note you can also get around this by resetting the component in the inspector, which should reset the array to the default string values.

I thought OP was getting an error message, but he wasn’t. The Inspector overriding the script values is completely normal behavior.

(To @OP)
The Inspector is there so you can set and view values in the Editor without having to go into the code. The value in the Inspector ALWAYS overrides what’s in the script. If you don’t want to see public variables in the Inspector, you can do this:

[HideInInspector] // Hides var below
public float hidden;
1 Like