# How can I change a materials properties in my Unity c# code?

Hello everyone I want to change my materials tiling offset in code, but the only way I found to access it other than drag-dropping to a public field in inspector is to check by name. But I then noticed the name is suffixed with ' (Instance)' .

So it seems a little odd to me having to access it this way, is there another way that I don't know about?

foreach(Material m in GetComponent<MeshRenderer>().materials)
{
if (m.name == "card_front (Instance)")
{
m.mainTextureOffset = new Vector2(value * 1/13f, (int)suit * 1/5f);
}
}


If you know the order of the materials you can just access the materials list like an array, if you only have one you can always use [0]. For example:

GetComponent<MeshRenderer>().materials[?].mainTextureOffset = new Vector2(value * 1/13f, (int)suit * 1/5f);


You also don't necessarily need to worry about the (instance) in the name if you use .StartWith. This will return true as long as the start of the string matches but anything after the text you pass in will be ignored so card_front2, card_front two, card_fronts (instacnce) will all pass. For example:

if (m.name.StartsWith("card_front"))


but linking to the material in the inspector isn't necessarily a bad thing as it decouples the material from the code so you don't need to change the code if someone goes in and changes the material for a different one or changes the name.

• awesome man thanks! The StartsWith() will be perfect for me. – Big T Larrity Jun 11 '19 at 18:29
• i must say i prefer not to assign the values via Inspector if i can help it. I have had quite a few times where they have lost the values somehow and I find myself always having to reassign them if I refactor variable names etc. Still a very helpful and complete answer thanks again – Big T Larrity Jun 11 '19 at 18:31
• @BigTLarrity note that if you rename a field, you can use the FormerlySerializedAs attribute to make sure it stays assigned in the inspector. – Ed Marty Jun 12 '19 at 1:30
• wow cheers Ed Marty, i will surely take a look at that – Big T Larrity Jun 12 '19 at 14:40