Color Problems. [Solved]

Trying to create this simple funcion:
Each time you press the Game Object, its changes the color, and switches between two colors(Off and On colors) becuase im randomizing the colors of the game object, I need to save the original color before the switch, but… its doesnt work. Im getting The color white insted of the game object’s color.
Heres the script:

    void OnMouseDown()
    {
        SwitchX();
        Check();
    }
    void SwitchX()
    {
        isActive = !isActive;
        print(isActive);
    }
    void Check()
    {
        if (isActive)
        {

            Rend.color = RealColor[0];
        }
        if (!isActive)
        {
            RealColor[0] = gameObject.GetComponent<Renderer>().material.color;
            Rend.color = c;
        }
    }

notes: IsActive is a bool, Rend is the Sprite Renderer, And c is the color i want to switch to.
right now, it switches to c perfectly, but when it needs to turn back to the original color, it just turns white.

Thanks!!!

Where do you save the original color when the click first happens?

Also, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

You can even print out colors and see what their RGB is.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run?
  • what are the values of the variables involved? Are they initialized?

Knowing this information will help you reason about the behavior you are seeing.

I didnt want to post the whole script here, becuase it has other uses too and is long, So i posted the part thats responsible for the color change, but i can say that. by the first time you press the object its already has his selected color, and you can see that in the OnMouseDown Funcion i call SwitchX and Check. SwitchX just switches the state of the variable “Is active” And the check funcion is doing the part that isnt working, if the IsActive bool is false it should save the curret gameobject’s color in the array RealColor and then change the color. And if IsActive is true, its should apply the RealColor’s Saved color to the gameObject.

also, theres an print in that script that prints the state of the variable IsActive, and its works. it switches the state everytime.

Ok i managed to find the problem, I was creating a game in 2D, therefore I needed to call GetComponent().color;
not: GetComponent().material.color;

1 Like

Oh yes! Nice distinction… I didn’t even consider that angle. Glad you’re up and running again.

1 Like