Tutorial: How to put together a MeshInstance + ShaderMaterial via script

novaleafnovaleaf Posts: 83Member
edited February 2 in Tutorials

This code is C#, but it's directly transferable to GDScript. Main "gotchas" are that you have to manually set shader default parameters, which you don't if you do this via the editor/inspector

        //put together a ShaderMaterial via code        
        var shader = GD.Load<Shader>("res://asset/cube/cube.shader");
        var diffuse = GD.Load<Texture>("res://asset/cube/cube-diffuse.png");
        var meshInstWithShadMat = new MeshInstance();
        meshInstWithShadMat.Mesh = mesh;
        var shadMat = new ShaderMaterial();
        shadMat.Shader = shader;
        //need to explicitly set default shader params yourself when setting up a ShaderMaterial through code
        shadMat.SetShaderParam("albedo", Colors.White);
        shadMat.SetShaderParam("uv1_scale", Vector3.One);
        shadMat.SetShaderParam("uv1_offset", Vector3.Zero);
        shadMat.SetShaderParam("uv2_scale", Vector3.One);
        shadMat.SetShaderParam("uv2_offset", Vector3.Zero);
        shadMat.SetShaderParam("texture_albedo", diffuse);
        meshInstWithShadMat.MaterialOverride = shadMat;
        AddChild(meshInstWithShadMat);

Tags :

Comments

Sign In or Register to comment.