Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding String properties in Unity Shaders

When creating a Shader in Unity, you can add a Property to it that can be called from inside of a different script. To do this, one could use the following line to call on and set a Vector3 Property names _vector3:

materialName.SetVector("_vector3", new Vector3(1, 1, 1));

This is great and all, but is there really not a way to avoid using 'magic' Strings? Seems like an awfully messy and error-prone way to do this. I get that maybe you could define it at the top so it is less of a 'magic' String, but it is still a string var that will need to be carried through from the Shader to the script when making any changes.

So pretty basic question here: Is there a way to avoid using 'magic' Strings when calling on variables in Unity?

like image 807
Jee Avatar asked Jun 08 '26 10:06

Jee


2 Answers

Sadly there is no way to avoid this. There is an elegant solution tho with IDs in mind for performance

public static class MyShader
{
    public static readonly int _MyPropertyName = 
        Shader.PropertyToID(nameof(_MyPropertyName));

}

Usage

void myShaderMethod()
{
    materialName.SetVector(MyShader._MyPropertyName, new Vector3(1, 1, 1));
}
like image 198
Menyus Avatar answered Jun 10 '26 19:06

Menyus


No, there is no way of getting rid of the string identifiers. Of course you can add some helper class containing your shader property identifiers in one place increasing maintainability.

public static class ShaderProps
{
    public static class MyShaderA
    {
        public const string SomeProperty = "_vector3";
    }
}

// Usage
public class MyBehaviour : MonoBehaviour
{
    private void Update 
    {
        material.SetVector(ShaderProps.MyShaderA.SomeProperty, ...);
    }
}

You should use Shader.PropertyToID(string name) and cache the result though, since it's more efficient. Unity calls it under the hood every time you use a string identifier making repeated calls with strings (e.g. in Update) unfavorable.

like image 26
Thomas Avatar answered Jun 10 '26 19:06

Thomas