Porting Colors From One Object to Another

Newbie here, trying to figure out the basics of Unity and coding in general.

The short and simple of it:
I have a script for a sprite called Object1 that chooses a color from a list of custom colors (for sake of example, a color called “Cortez’s Gold”) and then colors the sprite.

For reference, here is a small snippit of the script where it goes.

            ren = GetComponent<SpriteRenderer>();

void YellowColors()
    {
        Color CortezGold = new Color32(255, 230, 0, 255);
        YellowRandomNum = Random.Range(0, 10);

        if (YellowRandomNum == 0)
        {
            ren.material.color = CortezGold;
        }

Now the code I have - while ugly, poorly done (I’m basically doing the cursed YanDev “infinite else if” method), downright awful, and has undoubtedly brought great shame to my ancestors - does work. One day I’ll be a lot better at this and will figure out the proper way to do this, but for the moment I’m going with what’s functional as I get started.

The issue, then, is that Object2 needs to be able to use the same ren.material.color that Object1 is using. I tried using…

        ren = Object.GetComponent<Obj1script>().ren.material.color;

… but I get error code 0122, saying that “ren.material.color” (or even just “ren” by itself) is inaccessible due to its protection level.

I appreciate any help you can give me. Thanks in advance!

There isn’t enough code visible to determine what ren is but I will guess it has private scope. In any case (as you may have guessed) this is not the way to handle this. You essentially want 2 objects to have the same color (I assume) which suggests that a separate class could return the color and each object could set their own. They would be the same because they will use the same color source.

As you will be editing things… note that you define CortezGold locally prior to getting the random number and finding out whether you need it. So if it is == 0 that’s when you would instantiate and assign the color. But… have something return the color you want it set to instead.

1 Like