Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

Bug Graphics.DrawMeshInstanced applies MaterialPropertyBlock incorrectly

Discussion in 'General Graphics' started by Opeth001, Feb 25, 2021.

  1. Opeth001

    Opeth001

    Joined:
    Jan 28, 2017
    Posts:
    1,117
    Hello Everyone,

    DrawMeshInstanced API applies the first element of the MaterialPropertyBlock to all Rendered Entities.
    note: im using the URP SimpleLit shader.

    here is a simple example:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PropertiesTest : MonoBehaviour
    6. {
    7.  
    8.     public GameObject[] gameObjects;
    9.    
    10.     Vector4[] m_Float4ArrayBuffer = new Vector4[24];
    11.     Matrix4x4[] m_MatricesArray = new Matrix4x4[24];
    12.     Color color = Color.green;
    13.     Mesh mesh;
    14.     Material material;
    15.     MaterialPropertyBlock materialPropertyBlock;
    16.  
    17.     // Start is called before the first frame update
    18.     void Start()
    19.     {
    20.         if (gameObjects.Length == 0)
    21.             return;
    22.  
    23.         var firstElement = gameObjects[0];
    24.  
    25.         material = firstElement.GetComponent<MeshRenderer>().sharedMaterial;
    26.         mesh = firstElement.GetComponent<MeshFilter>().sharedMesh;
    27.  
    28.         materialPropertyBlock = new MaterialPropertyBlock();
    29.  
    30.         for (var i=0; i< gameObjects.Length; i++)
    31.         {
    32.             m_MatricesArray[i] = gameObjects[i].transform.localToWorldMatrix;
    33.             m_Float4ArrayBuffer[i] = color;
    34.         }
    35.  
    36.         m_Float4ArrayBuffer[0] = Color.red;
    37.         m_Float4ArrayBuffer[5] = Color.blue;
    38.  
    39.         materialPropertyBlock.SetVectorArray("_BaseColor", m_Float4ArrayBuffer);
    40.     }
    41.  
    42.     // Update is called once per frame
    43.     void Update()
    44.     {
    45.         Graphics.DrawMeshInstanced(mesh, 0,  material, m_MatricesArray, gameObjects.Length, materialPropertyBlock);
    46.  
    47.     }
    48. }
    49.  
    as you can see i applied different colors at indexes 0 and 5, but everything is rendred with first element Color (Red).