0
\$\begingroup\$

I have written a simple c# class that is supposed to change the color of the Player Renderer. But, there seems to be a problem! whenever I call the function OnCallFun() ... the color stays put and does not change. I have looked into the solution for quite some time now but no hope. does anyone have a solution?

using UnityEngine;

public class ChangeColor : MonoBehaviour
{

    // Reference to Sprite Renderer component
    private Renderer rend;


    [SerializeField]
    private Color colorToTurnTo = Color.white;



    // Use this for initialization
    void Start()
    {

        rend = GetComponent<Renderer>();

        // Change sprite color to selected color
        rend.material.SetColor("_SpecColor", colorToTurnTo);
    }
}

enter image description here

\$\endgroup\$
0
1
\$\begingroup\$

You are changing a material property called "_SpecColor" that the default sprite material does not use.

Did you mean to change the colour of the sprite renderer itself? This is more efficient than cloning the material to set unique material properties on the instance.

void Start()
{
    rend = GetComponent<SpriteRenderer>();
    rend.color = colorToTurnTo;
}

This is shown in the very first code sample in the documentation for SpriteRenderer, so be sure to check the docs when troubleshooting a problem!

\$\endgroup\$
0
0
\$\begingroup\$

If you want to use the Setter, you need to use the correct name of the color that is assigned.

 void Start() {    
    rend = GetComponent<Renderer>();
    rend.material.SetColor("_Color", colorToTurnTo);
 }

You can find the name of it when you follow the rend.material.color (which you can set directly as DMGregory posted) and it calls the setter from there.

Addition from DMGregory

Note that SpriteRenderer.color does not set Renderer.material.color. What it does instead is assign the colour you select as the vertex colours for the vertices of the sprite's polygon. That means you can still draw multiple sprites with different colours in a single draw call with a single material, rather than creating copies of the material with different colours for each one.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.