Skip to content

Instantly share code, notes, and snippets.

@ogrew
Last active May 13, 2022 17:59
Show Gist options
  • Save ogrew/d3858770cd97728d6fd5812a886e4c5a to your computer and use it in GitHub Desktop.
Save ogrew/d3858770cd97728d6fd5812a886e4c5a to your computer and use it in GitHub Desktop.
DrawMeshInstancedを試す(その2)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
public class DrawMeshInstanced_demo2 : MonoBehaviour
{
public int count = 1000;
public float radius = 5;
public Mesh copyMesh;
public Material material;
private List<Matrix4x4[]> batches;
private MaterialPropertyBlock block;
static readonly int MAX_CONT = 1023;
private void Start()
{
SetUp();
}
private void Update()
{
foreach (var batch in batches)
{
Graphics.DrawMeshInstanced(copyMesh, 0, material, batch, MAX_CONT, block);
}
}
private void SetUp()
{
batches = new List<Matrix4x4[]>();
block = new MaterialPropertyBlock();
var matrices = new Matrix4x4[MAX_CONT];
Vector4[] colors = new Vector4[count];
for (int i = 0; i < count; i++)
{
if (i % MAX_CONT == 0)
{
matrices = new Matrix4x4[MAX_CONT];
batches.Add(matrices);
}
Vector3 pos = Random.insideUnitSphere * radius;
Quaternion rot = Quaternion.Euler(
Random.Range(-180, 180),
Random.Range(-180, 180),
Random.Range(-180, 180)
);
Vector3 size = Vector3.one;
matrices[i % MAX_CONT].SetTRS(pos, rot, size);
matrices[i % MAX_CONT] = transform.localToWorldMatrix * matrices[i % MAX_CONT];
colors[i] = Color.Lerp(Color.magenta, Color.cyan, Random.value);
}
block.SetVectorArray("_Colors", colors);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment