Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice
  2. Ever participated in one our Game Jams? Want pointers on your project? Our Evangelists will be available on Friday to give feedback. Come share your games with us!
    Dismiss Notice

Weird Behavior when setting MaterialPropertyBlocks

Discussion in 'Shaders' started by sharkwithlasers, Mar 21, 2020.

  1. sharkwithlasers

    sharkwithlasers

    Joined:
    Dec 8, 2012
    Posts:
    7
    For my current project, I need to be able to set custom Material properties for each game object that I have.

    In order to do this, I tried to set `MaterialPropertyBlock` in each `MeshRenderer` like so:
    Code (CSharp):
    1. var props = new MaterialPropertyBlock();
    2. props.SetColor("_ObjectColor", new Color(
    3.     Random.Range(0f, 1f),
    4.     Random.Range(0f, 1f),
    5.     Random.Range(0f, 1f)
    6. ));
    7. GetComponent<MeshRenderer>().SetPropertyBlock(props);
    However, this did not do set anything until I changed the code to the following:
    Code (CSharp):
    1. var props = new MaterialPropertyBlock();
    2.  
    3. var mr = GetComponent<MeshRenderer>();
    4.  
    5. props.SetColor("_ObjectColor", new Color(
    6.     Random.Range(0f, 1f),
    7.     Random.Range(0f, 1f),
    8.     Random.Range(0f, 1f)
    9. ));
    10.  
    11. mr.SetPropertyBlock(props);
    Does anyone know why this would be the case? (It took me hours of trial and error in order to get to this).

    Thanks!
     
unityunity