建立一個 Cube,而後給這個 Cube 添加以下腳本。數組
using UnityEngine; using System.Collections; [RequireComponent(typeof(MeshFilter),typeof(MeshRenderer))] // 防止獲取組件失敗 public class ProceduralTextureTest : MonoBehaviour { // Use this for initialization void Start () { var material = GetComponent<MeshRenderer>().material; material.mainTexture = GenerateTexture(); } Texture2D GenerateTexture() { // 建立一個 128*128 的二維紋理 var texture = new Texture2D(128,128,TextureFormat.ARGB32, false); // 定義一個顏色數組 var colors = new Color[32*32]; for (int i = 0; i < colors.Length; ++i) { colors[i] = new Color(0,0,0,1); } // 在紋理左下角 32*32 的範圍繪製一塊黑色區域 texture.SetPixels(0,0,31,31,colors); // Apply 使設置生效 texture.Apply(false,false); return texture; } }
效果圖以下:ui