For each problem(solved)

Hello guys, I have a little problem with foreach if you can help me that will be great, so i wanted to write text with int values that are in an other array, like for text[0] the milestones is milestones[0] and for text[1] its milestones[1], sorry for my English haha, here the script.

public Text [] Texts;
    public int [] milestones;
    void Start()
    {
        foreach (Text text in Texts)
        {
            text.text = "NEED TO REACH A SCORE OF" + " " + milestones;
        }
    }

You need a for loop so you can index the other array.

A better solution would be to create a custom type that holds both values

2 Likes

Oh ok thanks for your answer dude

Right, this is for sure the better solution because it’s less error prone. Though it comes with a small drawback. First let me show an example how that solution may look like:

[System.Serializable]
public class MileStone
{
    public int score;
    public Text text;
}

public MileStone[] milestones;

void Start()
{
    foreach (MileStone ms in milestones)
    {
        ms.text.text = "NEED TO REACH A SCORE OF " + ms.score;
    }
}

Now you can simply expand the “milestones” array in the inspector, add the Text references and set the required score for each milestone. This has the additional advantage that you can not confuse indices or have more or less elements in one or the other array because now you only have one array. So it makes it easier to match up the milestone score value with its corresponding Text instance.

The only downside to this is, that you can no longer drag and drop several Text instances at once into the array since the array now contains our custom class and not Text component references. So the milestone Text objects have to be dragged in manually one by one. Of course one could write some editor code that handles multiple object drags, but that would be probably overkill and takes longer than assigning the Text fields manually.

Note you could to add an additional public string name; at the beginning of the MileStone class. That way the you can give each milestone a name which will be displayed in the inspector listing instead of “Element 0”. If the first variable inside such a serializable class is a string, the inspector will use it as label for the element in an array or List.

1 Like

Oh tha’ts a very interresting way to solve the problem,
I will try it(will 100% work)
thanks for your very detailed anwser , i really apreciated it. :slight_smile: