Help, adding to a list changes all items in the list to the new item!

I am wanting to take the inputs from the UI elements and place them into a list. When it adds the first item to the list there is no issue, but if I change the values then add them again to the list the first item also changes to the new values. I understand within the .Add() I think I need a ‘new’ but I don’t know what would need to come afterwards. I’ve included two screenshots at the bottom to better show whats going on.

public class QuestionGen : MonoBehaviour
{
    public InputField questionInput;
    public InputField answerAInput;
    public InputField answerBInput;
    public InputField answerCInput;

    public bool isAInput;
    public bool isBInput;
    public bool isCInput;

    public Question newQuestion;

    [SerializeField]
    private QuestionData _QuestionData = new QuestionData();

    // Start is called before the first frame update
    void Start()
    {
        isAInput = true;
    }

    public void IsAInput(bool isAInputD)
    {
        Debug.Log("Answer A: " + isAInputD);
        isAInput = isAInputD;
    }
    public void IsBInput(bool isBInputD)
    {
        Debug.Log("Answer B: " + isBInputD);
        isBInput = isBInputD;
    }
    public void IsCInput(bool isCInputD)
    {
        Debug.Log("Answer C: " + isCInputD);
        isCInput = isCInputD;
    }

    public void addToList()
    {
        newQuestion.questionName = questionInput.textComponent.text;
        newQuestion.answerA = answerAInput.textComponent.text;
        newQuestion.isA = isAInput;
        newQuestion.answerB = answerBInput.textComponent.text;
        newQuestion.isB = isBInput;
        newQuestion.answerC = answerCInput.textComponent.text;
        newQuestion.isC = isCInput;
        _QuestionData.questions.Add(newQuestion);
    }
}
//format of the questions within the game
[System.Serializable]
public class QuestionData
{
    public List<Question> questions = new List<Question>();
}

[System.Serializable]
public class Question
{
    public string questionName;
    public string answerA;
    public bool isA;
    public string answerB;
    public bool isB;
    public string answerC;
    public bool isC;
}

First item added

Second Item added

you need to create a new Question and add it to List,

you need to remove your

public Question newQuestion

and change your function to this

    public void addToList()
    {
        Question newQuestion = new Question();
        newQuestion.questionName = questionInput.textComponent.text;
        newQuestion.answerA = answerAInput.textComponent.text;
        newQuestion.isA = isAInput;
        newQuestion.answerB = answerBInput.textComponent.text;
        newQuestion.isB = isBInput;
        newQuestion.answerC = answerCInput.textComponent.text;
        newQuestion.isC = isCInput;
        _QuestionData.questions.Add(newQuestion);
    }
1 Like

Thank you it now works :smile: