I cannot change the color of cube directly

I was trying to change the color of cube like this.

using Interfaces;
using UnityEngine;

namespace Commands
{
    public class ClickCommand : ICommand
    {
        private Color _cubeColor;
        private readonly Color _color;

        public ClickCommand(GameObject cube, Color color)
        {
            _cubeColor = cube.GetComponent<MeshRenderer>().material.color;
            _color = color;
        }

        public void Execute()
        {
            _cubeColor = _color;

        }

        public void Undo()
        {
          
        }
    }
}

But it didn’t work. Then i tried this code.

using Interfaces;
using UnityEngine;

namespace Commands
{
    public class ClickCommand : ICommand
    {
        private readonly Material _cubeMaterial;
        private readonly Color _color;

        public ClickCommand(GameObject cube, Color color)
        {
            _cubeMaterial = cube.GetComponent<MeshRenderer>().material;
            _color = color;
        }

        public void Execute()
        {
            _cubeMaterial.color = _color;
        }

        public void Undo()
        {
        }
    }
}

And it worked. Why the first code didn’t work? I didn’t change anything except this code

In your first example you’re just changing some local color variables on your script. In the second example you’re actually changing the color on your cube’s material.

Color is a value type, meaning when you read its value you simply make a copy of it. Changes to that copy won’t affect the original.

Material is a reference type, which means when you read it, you get a reference to the real thing.

1 Like

If you read the docs on the material property, you will note that it makes a fresh copy of the material.

This fresh copy is just floating around and you’re changing its color. It has no relation to anything else, either the original cube it came from or anything else anywhere.

You can either a) modify the .sharedMaterial (BUT THIS IS SHARED!!!), or b) assign the new copy back to the cube once you have changed its color.