0
0
Unityframework~5 mins

Materials and textures in Unity

Choose your learning style9 modes available
Introduction
Materials and textures help make 3D objects look real by adding colors and surface details.
When you want to change how an object looks in your game.
When you want to add colors or patterns to walls, floors, or characters.
When you want to make surfaces look shiny, rough, or bumpy.
When you want to reuse the same look on many objects easily.
When you want to improve the visual style of your game.
Syntax
Unity
Material myMaterial = new Material(Shader.Find("Standard"));
myMaterial.mainTexture = myTexture;
Use Shader.Find to pick the type of material look you want.
Assign a Texture to the material's mainTexture to add an image on the surface.
Examples
Creates a red-colored material without any texture.
Unity
Material redMaterial = new Material(Shader.Find("Standard"));
redMaterial.color = Color.red;
Loads a brick image and applies it as a texture to a material.
Unity
Texture2D brickTexture = Resources.Load<Texture2D>("brick");
Material brickMaterial = new Material(Shader.Find("Standard"));
brickMaterial.mainTexture = brickTexture;
Assigns the brick material to the object's renderer to change its look.
Unity
Renderer renderer = gameObject.GetComponent<Renderer>();
renderer.material = brickMaterial;
Sample Program
This script creates a material with a wood texture and applies it to the object it is attached to. The texture must be placed in a Resources folder inside the Unity project.
Unity
using UnityEngine;

public class ApplyMaterial : MonoBehaviour
{
    void Start()
    {
        // Create a new material with the Standard shader
        Material newMaterial = new Material(Shader.Find("Standard"));
        
        // Load a texture named "wood" from Resources folder
        Texture2D woodTexture = Resources.Load<Texture2D>("wood");
        
        // Assign the texture to the material
        newMaterial.mainTexture = woodTexture;
        
        // Set the material color to white to show texture clearly
        newMaterial.color = Color.white;
        
        // Apply the material to this object's renderer
        Renderer renderer = GetComponent<Renderer>();
        if (renderer != null)
        {
            renderer.material = newMaterial;
        }
    }
}
OutputSuccess
Important Notes
Textures must be imported into Unity and placed in a Resources folder to load them at runtime.
Changing materials at runtime affects only the object you assign it to, not all objects sharing the material.
Use the Standard shader for most common material effects like color, texture, and shininess.
Summary
Materials define how objects look by controlling color and texture.
Textures are images applied to materials to add surface details.
You create materials with shaders and assign textures to them.
Apply materials to objects using their Renderer component.