Change the material color of an Object in Unity 3D
Hello programmers, In this article, I will show how to change the material color of an Object in Unity 3D.
Lets’s get started with the building process.
Step 1: Create a 3D Object
First, create a 3D Object. You can do this by right-clicking in Hierarchy, and selecting 3D Object > Sphere.
Game Object successfully created.
Step 2: Create a Material
Now create a material by right-clicking in the Assets window, and selecting Create > Material.
Now Material is successfully created.
Step 3: Drag and Drop the material
Now, drag and drop the material from the Assets window to the Sphere at Hierarchy.
Step 4: Create a button
Create a button by right-clicking in the Hierarchy window, and selecting UI > Button-TextMeshPro.
Adjust your button accordingly to your game.
Step 5: Create C# Script
Now create a C# script by right-clicking in the Assets window, and selecting Create > C# Script.
After creating the C# script, name it as ChangeColor, and write down the code below.
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChangeColor : MonoBehaviour { public Renderer sphereRenderer; public GameObject sphere; [SerializeField] private Color newColor; [SerializeField] private Color[] colors; private int colorValue; // Start is called before the first frame update void Start() { sphereRenderer = sphere.GetComponent<Renderer>(); } // Update is called once per frame void Update() { } public void ChangeMaterial() { newColor = Random.ColorHSV(); sphereRenderer.material.color = newColor; } }
Step 6: Add the C# script
Add the ChangeColor script to the Button. Now go to the Inspector window, select Button > On Click () > +.
In On Click ()
- Select Object > Scene > Button.
- Function > ChangeColor > ChangeMaterial() .
Now run the program.
Output:
Leave a Reply