Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved Change material in Renderer inside Particle System

Discussion in 'General Graphics' started by Monkey_M, Dec 21, 2020.

  1. Monkey_M

    Monkey_M

    Joined:
    Mar 10, 2020
    Posts:
    36
    Hi guys,
    As the title I would like to change the material in Renderer at runtime via script.
    What I'm trying to do is:
    Code (CSharp):
    1. ParticleSystem tmp = Instantiate(splatEffect, transform.position, Quaternion.identity);
    2. var rend = tmp.GetComponent<ParticleSystemRenderer>();
    3. rend.material = gameObject.GetComponent<MeshRenderer>().material;
    But no material is set. Am I doing something wrong?
     
    Last edited: Dec 22, 2020
    Volodemar likes this.
  2. Monkey_M

    Monkey_M

    Joined:
    Mar 10, 2020
    Posts:
    36
    Ok my stupid mistake was that i had an effect inside another so the solution and first access the child:
    Code (CSharp):
    1. ParticleSystem tmp = Instantiate(splatEffect, transform.position, Quaternion.identity);
    2. ParticleSystem newTmp = tmp.transform.GetChild(0).GetComponent<ParticleSystem>();
    3. var rend = newTmp.GetComponent<ParticleSystemRenderer>();
    4. rend.material = gameObject.GetComponent<MeshRenderer>().material;
     
    Last edited: Dec 22, 2020
    -chris likes this.
  3. richardkettlewell

    richardkettlewell

    Unity Technologies

    Joined:
    Sep 9, 2015
    Posts:
    2,240
    Also - always use sharedMaterial rather than material where possible
     
  4. Monkey_M

    Monkey_M

    Joined:
    Mar 10, 2020
    Posts:
    36
    Oh yes, I hadn't thought of it because of the rush.
    Thanks for the tip!
     
    richardkettlewell likes this.