Strange behavior when setting the color for a GameObject in Unity

Viewed 210

So i'm having this strange behavior when I set the color for a gameobject.

using UnityEngine;

public class TestObject: MonoBehaviour
{
private Material screenMaterial;

private void Awake()
{
    screenMaterial= transform.GetChild(0).GetComponent<SpriteRenderer>().material;
    screenMaterial.SetColor("_Color", Color.yellow);
}
}

enter image description here

The problem is the color is set to yellow correctly like 90% of the time and sometimes its just white. I mean the only thing that comes to my mind on why this happen is that there isn't enough time for the script to get the material component and then sets its color?!

This is a brand new 2D project and there no other scripts.

Any idea why this happen?

Here's the project file. Download. Made in unity 2019.2.18f1

4 Answers

It could be that the child is not always loaded in yet when Awake is called on this GameObject. I would try changing out Awake() for Start() and see if the problem persists.

You are currently trying to set the color of the material. Instead of doing that, just change the Color field seen in the SpriteRenderer Component below.

enter image description here

You can use the following code to adjust the color of a sprite:

public class TestObject: MonoBehaviour
{
    private Material screenMaterial;

    private void Awake()
    {
        transform.GetChild(0).GetComponent<SpriteRenderer>().color = Color.yellow;
    }
}

Hope this helps!

So I managed to solve the issue and its actually very simple, Since the TestObject is made out of 2 objects the first one is the parent and the second one is the child..

All I had to do is to change the sorting layers, so by setting the the sorting layer in the child object to 1 and the parent's to 0 FIXED THE ISSUE.

I hope this help some of you guys.

try

transform.GetChild(0).GetComponent<SpriteRenderer>().material.color = Color.yellow;

The way you are setting color is like for a custom shader, setting the "_Color" property of the shader

edit try this:

for (var child : Transform in transform) {
    child.GetComponent<SpriteRenderer>().material.color = Color.yellow;
}
Related