Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Question (new to scriping) Button to change object color

Discussion in 'Scripting' started by Orihadar, Jan 9, 2023.

  1. Orihadar


    Jul 16, 2015
    Greeting to all who can help me, I have a beginner question with scripting,
    after building it and compiling everything the script seems to not work, the script is attached to the UI Button, it has to compiling issues.
    I've created a new material for the Cube object - the goal of the script is to let the button to change color to any random color - seems to not work, I'll like to know what I did wrong, i've built this script by following a guide [shame that there's not a normal lesson about it in the Unity learning :( ]
    The material name is CubeMat
    the script is attached to the button and the cube it attached to the script function
    I've tried to move the script from the editor to the Assets folder, nothing seems to work
    this is my script, I'll be happy to know what am i mission, or if there are other videos or lesson that give better guidance and overall look on the entire buttons/ gui field, thanks to anyone who helps :)

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

    public class CubeScript : MonoBehaviour
    private GameObject Cube;

    private Renderer CubeRenderer;

    private Color newCubeColor;

    private float randomChannelOne, randomChannelTwo, randomChannelThree;

    // Start is called before the first frame update
    void Start()
    CubeRenderer = Cube.GetComponent<Renderer>();
    private void ChangeCubeColor()
    randomChannelOne = Random.Range(0f, 1f);
    randomChannelTwo = Random.Range(0f, 1f);
    randomChannelThree = Random.Range(0f, 1f);

    newCubeColor = new Color(randomChannelOne, randomChannelTwo, randomChannelThree, 1f);

    CubeRenderer.material.SetColor("_color", newCubeColor);

  2. Kurt-Dekker


    Mar 16, 2013
    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags:

    What shader is this? Is this your own?

    In any case the spelling and uppercase/lowercase of shader properties is critical.

    Right-click edit on the material to edit the shader and see its properties.

    For instance, the default standard shader has a
    property, NOT a