Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question (new to scriping) Button to change object color

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

  1. Orihadar

    Orihadar

    Joined:
    Jul 16, 2015
    Posts:
    1
    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
    {
    [SerializeField]
    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>();
    gameObject.GetComponent<Button>().onClick.AddListener(ChangeCubeColor);
    }
    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

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/

    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
    _Color
    property, NOT a
    _color
    property.