1

How do I automatically assign the length of an array based on the length of another and push a string to it? Such that in for loop when I copy the string, it will automatically get copied to all the array strings.

public string[] ArrayOfStrings;
public Image[] images;

void Start()
{
    for(int i = 0; i < images.Length; i++)
    {
        ArrayOfStrings[i] = "Testing String";
    }
}
1
  • If your arrays have always the same value. You could perform this loop on editor time by using the OnValidate() unity method. It's a good idea to make computation on editor mode when it's possible. Don't forget to call UnityEditor.EditorUtility.SetDirty(this) after your change on the OnValidation method to force serialization of your gameobject. Commented Oct 7, 2020 at 11:35

1 Answer 1

3
ArrayOfStrings = new string[images.Length];

Then you can do the loop

for(int i = 0; i < ArrayOfStrings.Length; i++)
{
    ArrayOfStrings[i] = "Testing String";
}

Or you can use List and linq. For example :

public List<string> ArrayOfStrings;
public List<Image> Images;

void Start()
{
    ArrayOfStrings.AddRange(Images.Select(x => $"the text you want for {x}").ToList());
}
Sign up to request clarification or add additional context in comments.

5 Comments

Yeah I was planning to go for List. Why is List better than array?
List can be extend easily because you don't have to specify the length of a list at instantiation. But it depend of what you want to do. Array can have better performance but if you don't make huge computation on a loop on update method. It would be acceptable to use list 99% of time. (Just my opinion) And I like to use linq for list manipulation like select data with conditions or transform data and so one.
"It would be acceptable to use list 99% of time" Disagree; you would use List<T> only if you require a resizable collection. Behaviour is the primary consideration, not performance.
Or in other words, use the most restrictive type possible that satisfies your requirements.
@JohnathanBarclay : Ok you make a point. This is why I wrote this is just my opinion. Because on my common usage of collection I often need resizable and easy to manipulation collection. I could not put word on my habit but your comment is perfect. Thank

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.