Introduction
Materials and textures help make 3D objects look real by adding colors and surface details.
Jump into concepts and practice - no test required
Material myMaterial = new Material(Shader.Find("Standard"));
myMaterial.mainTexture = myTexture;Material redMaterial = new Material(Shader.Find("Standard"));
redMaterial.color = Color.red;Texture2D brickTexture = Resources.Load<Texture2D>("brick"); Material brickMaterial = new Material(Shader.Find("Standard")); brickMaterial.mainTexture = brickTexture;
Renderer renderer = gameObject.GetComponent<Renderer>(); renderer.material = brickMaterial;
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; } } }
Material in Unity primarily control?GetComponent<Renderer>().material property of the Renderer component.Renderer rend = gameObject.GetComponent<Renderer>(); Texture2D tex = new Texture2D(128, 128); rend.material.mainTexture = tex; Debug.Log(rend.material.mainTexture.width);
mainTexture.width returns 128.Renderer rend = GetComponent<Renderer>(); Texture2D tex; rend.material.mainTexture = tex;
tex is declared but never assigned a texture object, so it is null.mainTexture will remove the texture, likely not intended and may cause issues.