- Home /
Getting item from List without a loop
Hello, I'm working on Loading and Saving for my game and I need to assign Materials back to GOs. I have a loop after loading that assigns the materials back to the loaded GOs using a list of Strings that is saved.
The for loop goes through the GOs and uses the Material list to assign mats using the String from the saved Materials names list.
But whenever the loop runs it uses the Material every material from the list, ending on the final material. Is there a way to get a Material from the list without using a Foreach Loop?
for (int i = 0; i < GOobj.Count; i++)
{
foreach (string matName in matNames)
{
foreach(Material matDB in this.gameObject.GetComponent<itemDataBase>().mats)
{
if (matDB.name == matName.Trim())
{
plaster[i].gameObject.GetComponent<MeshRenderer>().material = matDB;
}
}
}
}
I just need to get the correct Mat from the list. I thought that the line if (matDB.name == matName.Trim()) would make sure the correct Material is used and not all of them.
Does this make sense?
Thank you for any help.
Answer by GrayLightGames · Oct 11, 2019 at 09:53 PM
How are the matNames related to the GOobj? If they are just matched by having the same index in their respective lists, then you want to remove the first foreach statement and compare matDB.name == matNames[i]. You might even make the GOobj a custom class and store the name on it so you don't have a separate list you need to keep in sync. Just a suggestion, hope that helps!
I feel stupid now! Thank you for the advice. It is now working.
Glad that solved it! Haha no need to feel stupid, it's working now. Stupid would be giving up. Good luck with your project!
Your answer
![](https://koobas.hobune.stream/wayback/20220612213317im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Problem with showing "infinite saves" menu 0 Answers
Problem when saving and loading 1 Answer
Dynamically saving and loading player-created prefabs 0 Answers
Distribute terrain in zones 3 Answers