C# Array Of Class Read Variables

Hello I have a problem. I’ve made an class array, wich contains a bunch of variables. but the problem is that i don’t know how to read the variables from the array.

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

[System.Serializable]
public class Replies
{
	public string ReplyName;
	public int nextScenarioID;
}

public class scenario : MonoBehaviour 
{
	public int ScenarioID;
	public Replies[] Replies;

	// Update is called once per frame
	void Update () 
	{
		GameObject.Find("ButtonOneChoiceText").GetComponent<Text>().text = "" + Replies[0];
		GameObject.Find("ButtonTwoChoiceText1").GetComponent<Text>().text = "" + Replies[1];
		GameObject.Find("ButtonTwoChoiceText2").GetComponent<Text>().text = "" + Replies[2];
	}
}

so the problem is to set the text components to the corresponding reply. but it has multiple variables, and i don’t really get how to select the one i want. so in this case, "ButtonOneChoiceText"s text component should be “Yes”, "ButtonTwoChoiceText1"s text component should be “No”, and so forth.

Thanks for reading this, Cheers

//Gaffa

Use replies[0].replyName and replies[0].nextScenarioID

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
 
 [System.Serializable]
 public class Replie
 {
     public string replyName;
     public int nextScenarioID;
 }
 
 public class scenario : MonoBehaviour 
 {
     public int scenarioID;
     public Replie[] replies;
 
     // Update is called once per frame
     void Update () 
     {
         if (replies.Length != 0) {
			 foreach(Replie repl in replies) {
				 Debug.Log(repl.replyName+" "+repl.nextScenarioID);
			 }
		 }
     }
 }

Answer

Consider adding a variable to your Replies class of type Text; you can then use this variable to assign the different Text components to the string values.

Then in your Scenario class, in Start you could iterate through the array, and call a method to set up the text components;

public class Reply
{
    [SerializeField]
    private string m_replayName;
    [SerializeField]
    private int m_nextScenario;
    [SerializeField]
    private Text m_text;
    
    public void Setup()
    {
        m_text.text = m_replayName;
    }
}

public class Scenario
{
    [SerializeField]
    private Reply[] m_replies;

    public void Start()
    {
        foreach(Reply r in replies)
            r.Setup();
    }
}

Advice/Tips

  1. Use the SerializeField attribute to expose (view) private variables in the Inspector, and where needed create a method to get/set the value of this private variable. (private variables are generally best practice, if you want to know more watch this tutorial on encapsulation [video in Java, but it’s about the concept of Encapsulation])
  2. When naming classes, generally people use the singular version of a word (general coding convention).

Hope this helped in addition to the previous answer.