PhiCato
PhiCato

Reputation: 43

Unity - my array is not updating its elements

I'm making my first app in Unity to learn English words and I got stuck. I created and array like that:

public string[] words = {
    "apple",
    "banana",
    "big",
    "blue",
    "book",
    "one",
    "two"
};

I'm using PlayerPrefs to save which array element I'm learning at the moment. The problem is that I can't add or remove elements from this array. Whatever I do it always shows these 7 elements. Can you please tell me why?

The thing is I don't want to add elements dynamically or within the script. I just want to expand my array manually by adding more elements, like this:

public string[] words = {
    "apple",
    "banana",
    "big",
    "blue",
    "book",
    "one",
    "two",
    "colours",
    "green",
    "orange",
    "pencil",
    "yellow",
    "four",
    "five",
    "six",
    "small",
};

The thing is that after changing array from my first post to this one, change takes no effect. Program still sees only 7 elements. I tried to delete some elements and the result is the same. It looks like the program holds my array in memory or something....

Here is my complete code:

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

public class GameManager : MonoBehaviour {

    public static GameManager instance;
    public bool isLearnOn;
    public bool isFrontMenuActive;
    public GameObject frontMenuEmpty;
    Animator frontMenu;
    Animator finishPanel;

    //Tasks Elements
    Image taskImage;
    GameObject taskImageEmpty;
    GameObject taskAllElementsEmpty;
    GameObject taskTextEmpty;
    Text taskText;
    InputField taskInputField;
    AudioSource taskAudio;
    int randomWord;
    int wordCount;
    int allWordsCount;
    int collectPoint;
    Text pointsBoard;
    Text hint;
    public bool isHintShown;
    GameObject hintTextEmpty;
    int innerTaskCount;
    public bool isFinishPanelOn;



    void Awake(){
        if (instance == null) {
            instance = this;
        }
    }

    void Start () {
        collectPoint = (PlayerPrefs.GetInt ("points"));
        isLearnOn = false;
        //Variable assignment
            //Tasks Elements 
        taskAllElementsEmpty = GameObject.Find ("TaskAllElementsEmpty");
        taskImage = GameObject.Find ("TaskImage").GetComponent <Image>();
        taskTextEmpty = GameObject.Find ("TaskTextEmpty");
        taskText = GameObject.Find ("TaskText").GetComponent <Text>();
        taskInputField = GameObject.Find ("TaskInputField").GetComponent <InputField>();
        taskAudio = GameObject.Find ("GameManager").GetComponent <AudioSource>();
        pointsBoard = GameObject.Find ("PointsBoard").GetComponent <Text>();
        hint = GameObject.Find ("Hint").GetComponent <Text>();
        hintTextEmpty = GameObject.Find ("HintTextEmpty");
        finishPanel = GameObject.Find ("FinishPanel").GetComponent <Animator>();
        taskImageEmpty = GameObject.Find ("TaskImageEmpty");

        frontMenuEmpty = GameObject.Find ("FrontMenuEmpty");
        frontMenu = GameObject.Find ("FrontMenuEmpty").GetComponent <Animator>();

        pointsBoard.text = collectPoint.ToString ();

        allWordsCount = words.Length;
        Debug.Log (allWordsCount);

        isFrontMenuActive = false;

        FrontMenuShowHide ();
        taskAllElementsEmpty.SetActive (false);
        isHintShown = false;
        hint.text = "";
        innerTaskCount = 0;
        isFinishPanelOn = false;
        //TODO  Disable finisih panel


    }


    void Update () {
        if (isLearnOn == true) {
            if (wordCount < allWordsCount) {
                if  ((taskInputField.text == words [wordCount]) && innerTaskCount == 0) {
                    Task1 ();
                    taskText.text = "";
                    taskInputField.placeholder.GetComponent<Text>().text = "What is it?";
                    innerTaskCount = 1;

                } 
                else if  ((taskInputField.text == words [wordCount]) && innerTaskCount == 1) {
                    Task1 ();
                    taskText.text = "";
                    taskInputField.placeholder.GetComponent<Text>().text = "Listen and type the word down";
                    taskImageEmpty.SetActive (false);
                    innerTaskCount = 2;
                }

                else if ((taskInputField.text == words [wordCount]) && innerTaskCount == 2){
                    if (isHintShown == false) {
                        CollectPoints ();
                        NextTask ();
                        Debug.Log (wordCount);
                        innerTaskCount = 0;
                    } else {
                        NextTask ();
                        innerTaskCount = 0;
                    }
                }
            } else {

                if(isFinishPanelOn == false){
                    HideFinishPanel ();
                    wordCount = 0;
                }


            }

        } else {
            if (taskInputField.text == words [randomWord]) {

                if (isHintShown == false) {
                    CollectPoints ();
                    RandomTask ();
                } else {
                    RandomTask ();
                }
            }
        }

    }

    public void FrontMenuShowHide(){
        if (isFrontMenuActive == true) {
            frontMenu.Play ("FrontMenuOut");
            isFrontMenuActive = false;
        } else {
            frontMenu.Play ("FrontMenu");
            isFrontMenuActive = true;

        }
    }



    public void Task1(){
        isHintShown = false;
        wordCount = (PlayerPrefs.GetInt ("wordCountPrefs"));
        taskAllElementsEmpty.SetActive (true);
        taskText.text = words[wordCount];
        taskInputField.text = "";
        taskInputField.ActivateInputField ();
        //SoundPlay ();
        LoadPicture ();
        taskTextEmpty.SetActive (true);
        hint.text = "";
        taskInputField.placeholder.GetComponent<Text>().text = "Copy the word, please...";
        string path = "audio/" + words [wordCount];
        taskAudio.clip = (AudioClip)Resources.Load(path, typeof(AudioClip));
        taskAudio.Play ();
        taskImageEmpty.SetActive (true);
    }

    public void RandomTask(){
        isHintShown = false;
        randomWord = Random.Range (0, allWordsCount);
        taskAllElementsEmpty.SetActive (true);
        taskText.text = words[randomWord];
        taskInputField.text = "";
        taskInputField.ActivateInputField ();
        //SoundPlay ();
        LoadRandomPicture ();
        taskTextEmpty.SetActive (false);
        hint.text = "";
        taskImageEmpty.SetActive (true);
        taskInputField.placeholder.GetComponent<Text>().text = "What is it?";
        string path = "audio/" + words [randomWord];
        taskAudio.clip = (AudioClip)Resources.Load(path, typeof(AudioClip));
        taskAudio.Play ();
    }


    public void SoundPlay(){
        if (isLearnOn == true) {
            string path = "audio/" + words [wordCount];
            taskAudio.clip = (AudioClip)Resources.Load(path, typeof(AudioClip));
            taskAudio.Play ();
        } else {
            string path = "audio/" + words [randomWord];
            taskAudio.clip = (AudioClip)Resources.Load(path, typeof(AudioClip));
            taskAudio.Play ();
        }

    }

    public void LoadPicture(){
        string path = "img/" + words [wordCount];
        taskImage.sprite = (Sprite)Resources.Load(path, typeof(Sprite));
    }


    public void LoadRandomPicture(){
        string path = "img/" + words [randomWord];
        taskImage.sprite = (Sprite)Resources.Load(path, typeof(Sprite));
    }

    public void NextTask(){
        wordCount++;
        PlayerPrefs.SetInt ("wordCountPrefs", wordCount);
        Task1 ();
    }


    public void LearnIsOn(){
        isLearnOn = true;
    }
    public void LearnIsOff(){
        isLearnOn = false;
    }

    public void CollectPoints(){
            collectPoint++;
            PlayerPrefs.SetInt ("points", collectPoint);
            pointsBoard.text = collectPoint.ToString ();
    }

    public void ShowHint(){

        if (isLearnOn == true ) {
            if (innerTaskCount != 0){
                hint.text = words [wordCount];
                isHintShown = true;
            }

        } else {
            hint.text = words [randomWord];
            isHintShown = true;

        }
    }

    public void HideFinishPanel(){
        if (isFinishPanelOn == true) {
            finishPanel.Play ("FinishPanelOut");
            isFinishPanelOn = false;
        } else {
            finishPanel.Play ("FinishPanel");
            isFinishPanelOn = true;
        }


    }



    public string[] words = {
        "apple",
        "banana",
        "big",
        "blue",
        "book",
        "one",
        "two",
        "colours",
        "green",
        "orange",
        "pencil",
        "yellow",
        "four",
        "five",
        "six",
        "small",
    };

}

`

Upvotes: 0

Views: 3341

Answers (3)

derHugo
derHugo

Reputation: 90590

If you want to be able to do both, adding elements in the editor and by script you should rather use a List<string> words and check if the value already exists in the list before adding it in the script:

[SerializeField]
private List<string> words = new List<string>();

private void Start(){
    if(!words.Contains("apple")){
        words.Add("apple")
    }

    if(!words.Contains("banana")){
        words.Add("banana")
    }
}

Independent from that, if you want to update the List/Array also within the Editor I recomend you use the [ContextMenu] tag:

e.g. for your array:

public string[] words; // you don't set it here but expect it to be set in the editor

[ContextMenu("Import scripted array")]
private void ImportScriptedArray(){
    // Note in this case I simply overwrite any setting within the editor
    // There are multiple ways to prevent this like before using List or other methods
    words = new [] {
        "bla",
        "bli",
        "blub"
    };
}

This adds the method ImportScriptedArray to the context menu of this component in the editor. So first you have this unset array:

unset array

On your script/component you now can click on the settings icon to open the context menu.

method in context menu

And in the context menu click on your just generated Import Scripted Array to import your array from the script.

imported array

Upvotes: 1

Cenkisabi
Cenkisabi

Reputation: 1076

This happens because Unity initialize serialized public objects itself. When you define your variable first time in script if you initialized it manually, Unity serialize it with your values. Else Unity serialize it with default values.

For example. When you create the script below first time like;

public class GameManager : MonoBehaviour {

public string[] words = {
        "one",
        "two",
        "three",
        "four",
        "five",
        "six",
    };
}

Unity serialize words with this values. After that even if you change initial values from script, next time you run, it actually doesn't change.

For this, there are two options. First; define your variable in script with [System.NonSerialized] attribute.

[System.NonSerialized] public string[] words = {};

Second choice, select the gameobject from hierarchy. On inspector, chose your scripts component and Reset it when you change initial variables.

Upvotes: 2

vanshika
vanshika

Reputation: 411

You need to use list in place of array. List allows you to add or delete any item.

 List <string> names = new List<string>();

 Void Start()
    {
          names.Add(“apple”); 

  }

Upvotes: 1

Related Questions