- Home /
Is it possible to access an Object in an Object array by name ?
If we have an array of Objects , each object i nthe array has its own name . can we actually access an object in that array using its name ?
UnityEngine.Object[] all = AssetDatabase.LoadAllAssetsAtPath("Assets/SomeAsset.asset");
all[?]
I need to be able to access the objects by name how can I do this ?
Answer by rlo · Oct 25, 2015 at 11:41 PM
Have you tried iterating through the array:
Object[] all = AssetDatabase.LoadAllAssetsAtPath("Assets/SomeAsset.asset");
for(int i = 0; i < all.Length; i++)
{
if(all[i].name == "Foo")
{
}
}
Answer by Jiraiyah · Oct 29, 2015 at 12:49 PM
I would use linq in these conditions, works similar but in my opinion reads easier and works faster, although some people argue that linq is slower than simple for loop, but that is related to how unity converts the code to IL and hopefully in near future with IL2CPP it will be solved, if you would compile your code in visual studio to a dll for example, you would see that in most cases linq would be faster. the code would be something like this :
Object[] all = AssetDatabase.LoadAllAssetsAtPath("Assets/SomeAsset.asset");
var assetWithName = all.FirstOrDefault(t => t.name == "the name you look for");