Search Unity

How I can change Sprite Renderer color with C#? I need use RGB color.

Discussion in '2D' started by DredWolf, Oct 17, 2020.

  1. DredWolf

    DredWolf

    Joined:
    Oct 17, 2020
    Posts:
    1
    GetComponent<SpriteRenderer>().color = ... and what I can write after?
     

    Attached Files:

  2. Lo-renzo

    Lo-renzo

    Joined:
    Apr 8, 2018
    Posts:
    1,514
    Untitled - Copy.png
    Change the RGB 0-255 to RGB 0-1.0. This will allow you to get the correct float values to assign like so:
    spriteRenderer.color = new Color(1f, 1f, 1f, 1f); // this is white with zero transparency


    You could also use 0-255 scale if you use Color32, which is the 32-bit version of a color.
    spriteRenderer.color = (Color)(new Color32(228, 80, 80, 255));

    This explicitly converts Color32 to Color. You can probably eliminate the (Color) because there's an implicit operator that can convert it automatically. I've included it just to be clear about what's happening behind the scenes.
     
    SalihToker and cloud02468 like this.
  3. MrPaparoz

    MrPaparoz

    Joined:
    Apr 14, 2018
    Posts:
    157
    This should/may give you an idea.

    Code (CSharp):
    1. public class ColorChanger : MonoBehaviour {
    2.     public SpriteRenderer spriteRendererToChangeColor;
    3.     public Color colorYouWant;
    4.  
    5.     private void Awake(){
    6.         spriteRendererToChangeColor = GetComponent<SpriteRenderer>();
    7.     }
    8.  
    9.     private void Start(){
    10.         ChangeColor(colorYouWant);
    11.     }
    12.  
    13.     public void ChangeColor(Color color){
    14.         spriteRendererToChangeColor.material.color = color;
    15.     }
    16. }