Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Question Changing material color through object parent.

Discussion in 'Scripting' started by HighlordMagikarp, May 23, 2024.

  1. HighlordMagikarp

    HighlordMagikarp

    Joined:
    May 23, 2024
    Posts:
    1
    So, I'm making a project where cubes can be generated in runtime with different parameters. The relevant parts of it are the cube's color and text that is suspended above the cube using a canvas and several textmeshpro labels.

    During runtime at program start, I am changing the cubes color with the following code;

    MeshRenderer ren = GetComponentInChildren<MeshRenderer>();
    Color dieColor = new Color(r, g, b);
    ren.material.color = dieColor;

    The code is run from an empty parent object and the cube is a child(so is the canvas. The cube and canvas are not children of each other, just the empty parent object).

    The problem is that the color is rendered over the text from the canvas. This only happens because of me changing the material color. How can I get it so the material color isn't rendered above everything else?

    (Also in case it isn't obvious: I am very new to unity and coding for it in general so I expect I made some stupid goofs here.)
     
  2. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,214
    Screenshots would help. The only thing that I can figure from this is that your shaders for text and cube do not sort properly, likely because one is set to transparent and the other is opaque, but I'm not sure why setting the cube's material color would provoke this behavior.

    Also do not use
    material
    property, use
    sharedMaterial
    instead. (
    material
    will clone the existing material, sometimes you want this to happen if you want to affect just one instance, but usually you just want to change the color.)