0
\$\begingroup\$

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);
    }
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\begingroup\$ awesome man thanks! The StartsWith() will be perfect for me. \$\endgroup\$ Commented Jun 11, 2019 at 18:29
  • \$\begingroup\$ 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 \$\endgroup\$ Commented Jun 11, 2019 at 18:31
  • 2
    \$\begingroup\$ @BigTLarrity note that if you rename a field, you can use the FormerlySerializedAs attribute to make sure it stays assigned in the inspector. \$\endgroup\$
    – Ed Marty
    Commented Jun 12, 2019 at 1:30
  • \$\begingroup\$ wow cheers Ed Marty, i will surely take a look at that \$\endgroup\$ Commented Jun 12, 2019 at 14:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .