Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Recognize random colors help with script

Discussion in 'Scripting' started by petizero, Sep 11, 2019.

  1. petizero

    petizero

    Joined:
    Jan 1, 2019
    Posts:
    11
    Basically i have two sprites and i give the first one a random color, and i want the second color to be the same just with a darker tone is there any way to do that?

    This is the script i use to give the first sprite a color

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class changecolor : MonoBehaviour
    {
    public SpriteRenderer SpriteRenderer;
    void Start()
    {
    if (SpriteRenderer != null)
    {
    Color newColor = new Color(
    Random.value,
    Random.value,
    Random.value
    );


    SpriteRenderer.color = newColor;

    }

    }

    // Update is called once per frame
    void Update()
    {

    }
    }
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    6,662
    Use code tags, it's the first sticky on the forum.

    You can make a darker color something like this:
    Code (csharp):
    1. float someMultiplier = 0.5f;
    2. Color darkerColor = new Color(newColor.r * someMultiplier, newColor.g * someMultiplier, newColor.b * someMultiplier);
     
  3. petizero

    petizero

    Joined:
    Jan 1, 2019
    Posts:
    11
    Sorry about that im quite new to unity

    By the way the sprites i use are two different ones which have two different sprite renderers
    so how do i make a reference from the first script to the second?
     
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    6,662
    You can just have a second public SpriteRenderer reference. (By the way: it's strongly discourage to use the class name as the variable name; this can cause not only confusion but also compile issues, as the compiler will have to work out whether you're referring to a class function or a function on an instance.) A common standard in Unity, if you do want the variable to have the same name, is to use UpperCase for the class name vs camelCase for variable names.
    Code (csharp):
    1. public SpriteRenderer spriteRenderer;
    2. public SpriteRenderer spriteRendererDarker;
    3.  
    4. void Start() {
    5. // blah blah
    6. spriteRenderer.color = newColor;
    7. spriteRendererDarker.color = darkerColor;
    8. }
     
  5. petizero

    petizero

    Joined:
    Jan 1, 2019
    Posts:
    11
    Thaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaank you!
     
  6. Dameon_

    Dameon_

    Joined:
    Apr 11, 2014
    Posts:
    529
    Not to derail, but the compiler has no problem using context to figure out which you mean. I've never broken the compiler by naming my variables the same name as the class they implement. If you're using an IDE, there should be no confusion when reading, because it should be colored differently based on what it refers to.