using UnityEngine; [System.Serializable] public struct GridCellConfig { public Vector2 position; public Vector2 scale; public float rotation; public float textureIndex; public Vector2 offset; public float blend; } public class DynamicGridTextureController : MonoBehaviour { public Texture2DArray textureArray; public Material material; public Vector2Int gridSize = new Vector2Int(2, 2); public float tilingScale = 1f; private const int MAX_GRID_CELLS = 4; private GridCellConfig[] cellConfigs; void OnEnable() { InitializeGrid(); } void InitializeGrid() { // 创建三个:红色,蓝色,绿色的2x2的Texture2DArray textureArray = new Texture2DArray(2, 2, 2, TextureFormat.RGBA32, false); int totalCells = Mathf.Min(gridSize.x * gridSize.y, MAX_GRID_CELLS); cellConfigs = new GridCellConfig[totalCells]; // 设置默认配置 for (int i = 0; i < totalCells; i++) { cellConfigs[i] = new GridCellConfig { position = new Vector2(i % gridSize.x, i / gridSize.x), scale = Vector2.one, rotation = 0f, textureIndex = i % textureArray.depth, offset = Vector2.zero, blend = 1f }; } UpdateMaterial(); } public void UpdateCellConfig(int x, int y, GridCellConfig newConfig) { int index = y * gridSize.x + x; if (index < cellConfigs.Length) { cellConfigs[index] = newConfig; UpdateMaterial(); } } void UpdateMaterial() { if (material != null) { Vector4[] cellData = new Vector4[MAX_GRID_CELLS * 2]; for (int i = 0; i < cellConfigs.Length; i++) { var config = cellConfigs[i]; // 打包数据到Vector4数组 cellData[i * 2] = new Vector4( config.position.x, config.position.y, config.scale.x, config.scale.y ); cellData[i * 2 + 1] = new Vector4( config.rotation, config.textureIndex, config.offset.x, config.offset.y ); } material.SetVectorArray("_CellData", cellData); material.SetVector("_GridConfig", new Vector4(gridSize.x, gridSize.y, 0, 0)); material.SetFloat("_TilingScale", tilingScale); } } }