I’m having trouble with GPU instanced objects. I use this script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GPUInstancing : MonoBehaviour
{
public Mesh mesh; // Mesh to be instanced
public Material material; // Material supporting instancing
public int instanceCount = 500; // Number of instances
public Vector3 areaSize = new Vector3(10, 0, 10); // Spread of instances
private List<Matrix4x4> matrices; // Transformation matrices for instances
void Start()
{
// Initialize transformation matrices
matrices = new List<Matrix4x4>(instanceCount);
for (int i = 0; i < instanceCount; i++)
{
// Random position within the specified area
Vector3 position = new Vector3(
Random.Range(-areaSize.x / 2, areaSize.x / 2),
Random.Range(-areaSize.y / 2, areaSize.y / 2),
Random.Range(-areaSize.z / 2, areaSize.z / 2)
);
// Random rotation and scale
Quaternion rotation = Quaternion.Euler(0, Random.Range(0, 360), 0);
Vector3 scale = Vector3.one;
// Create transformation matrix
Matrix4x4 matrix = Matrix4x4.TRS(position, rotation, scale);
matrices.Add(matrix);
}
}
void Update()
{
// Draw instances
Graphics.DrawMeshInstanced(mesh, 0, material, matrices);
}
}
The instanced objects does not show material. Only solid color which changes (white->gray->red->etc…) based on the viewing angle. Any ideas why it behaves like this?
