Search Unity

How to change Material Property Block for Particle System?

Discussion in 'Scripting' started by Ziya, Aug 23, 2019.

  1. Ziya

    Ziya

    Joined:
    Aug 30, 2013
    Posts:
    65
    Why does changing Texture of Particle System using Material Property Block changes texture, but Particle System is still emitting old texture?

    I try the code in Start, checking in Editor shows new texture, but Particle System still emits old texture. The script works for SpriteRenderer, but not ParticleSystem. I tried to Play/Stop emission - no difference.

    Code (CSharp):
    1.     ParticleSystemRenderer renderer = gameObject.GetComponent<ParticleSystemRenderer>();
    2.     MaterialPropertyBlock materialPropertyBlock = new MaterialPropertyBlock();
    3.     renderer.GetPropertyBlock(materialPropertyBlock);
    4.     materialPropertyBlock.SetTexture("_MainTex", texture);
    5.     renderer.SetPropertyBlock(materialPropertyBlock);
     
    Last edited: Aug 23, 2019
  2. madGlory

    madGlory

    Joined:
    Jan 12, 2016
    Posts:
    44
    I was able to make this work with this script in unity 2019.4.15:

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. [ExecuteAlways]
    4. [RequireComponent(typeof(Renderer))]
    5. public class PropertyBlockImageSetter : MonoBehaviour {
    6.  
    7.     public Texture2D texture;
    8.  
    9.     [SerializeField]
    10.     private Renderer rend;
    11.  
    12.     private MaterialPropertyBlock propertyBlock;
    13.  
    14.     void Awake() {
    15.  
    16.         propertyBlock = new MaterialPropertyBlock();
    17.  
    18.     }
    19.  
    20.     // Start is called before the first frame update
    21.     void Update() {
    22.  
    23.         rend.GetPropertyBlock(propertyBlock, 0);
    24.         propertyBlock.SetTexture("_MainTex", texture);
    25.         rend.SetPropertyBlock(propertyBlock, 0);
    26.  
    27.     }
    28.  
    29.     private void Reset() {
    30.  
    31.         if (rend == null) {
    32.             rend = GetComponent<Renderer>();
    33.         }
    34.  
    35.     }
    36.  
    37. }
     
    DragonCoder likes this.