Is it possible to have a variable parameter in a Unity class?
For example:
gameObject.transform.GetComponent<Renderer>().material.SetTexture("_MainTex", "m_number" + i);
Is it possible to have a variable parameter in a Unity class?
For example:
gameObject.transform.GetComponent<Renderer>().material.SetTexture("_MainTex", "m_number" + i);
When “ i “ is a string.
In the particular example no.
but if the variable parameter was taking string then it i would have to be assembled with the rest of the parameter as a string
You probably come from a dynamic scripting language background where you can simply “compose” variable names dynamically on the fly. While it is possible to use reflection in C# to achieve some of that functionality, C# is a statically compiled language and generally doesn’t allow to do such things. However there are almost always better alternatives. It seems you want to be able to select a certain texture based on your index “i”? If that’s the case, you should create a Texture2D array (public Texture2D[ ] textures;
). You can assign several textures to that array in the inspector and choose one element based on the 0-based index.
....SetTexture("_MainTex", textures[i]);
This assumes that “i” is an integer between 0
and textures.Length-1
. So if you have 3 textures in the array, valid indices are 0, 1 or 2
Thanks @AnimalMan and @Bunny83 ! I am actually learning C# and Javascript atthe same time.
I’m going to try this in a for loop.
On the flip side let’s say he made a bunch of custom materials in game and saved the modified variables to a file. And was using the left* side of the parameter
<Renderer>().material.SetTexture("_MainTex" + i.ToString(), textures[x])
yes
Is all possible