Still struggling with Unity’s graphics pipeline, sigh.
Trying to draw some instanced meshes from the view of a camera. I only want to render these meshes in the supplied camera, but for some obvious and clearly documented reason, the meshes won’t render when a camera is supplied.
Some simple code: Listen for the preCull event, Draw instanced meshes.
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
[ExecuteInEditMode]
public class GraphicsTest : MonoBehaviour {
public Mesh mesh;
public Material material;
public int instances = 1;
public bool renderWithCamera = false;
private Matrix4x4[] matrices;
private MaterialPropertyBlock properties;
private void OnEnable() {
Camera.onPreCull -= DrawWithCamera;
Camera.onPreCull += DrawWithCamera;
}
private void OnDisable() {
Camera.onPreCull -= DrawWithCamera;
}
private void DrawWithCamera(Camera camera) {
if (camera) {
Draw(camera, camera.transform.localToWorldMatrix * Matrix4x4.TRS(Vector3.forward * 10, Quaternion.identity, Vector3.one));
}
}
private void Draw(Camera camera, Matrix4x4 matrix) {
if (mesh && material) {
if (instances > 1) {
material.enableInstancing = true;
if (matrices == null || matrices.Length != instances) {
matrices = new Matrix4x4[instances];
}
if (properties == null) {
properties = new MaterialPropertyBlock();
}
for (int i = 0; i < instances; i++) {
matrix = Matrix4x4.TRS(camera.transform.TransformPoint(3 * i, 0, 5 + i * 10), Quaternion.identity, Vector3.one);
matrices[i] = matrix;
}
if (!renderWithCamera) {
//Will Render, but meshes are drawn in every camera :(
Graphics.DrawMeshInstanced(mesh, 0, material, matrices, instances, properties, ShadowCastingMode.Off, false, gameObject.layer, null);
}
else {
//Won't Render
Graphics.DrawMeshInstanced(mesh, 0, material, matrices, instances, properties, ShadowCastingMode.Off, false, gameObject.layer, camera);
}
}
else {
material.enableInstancing = false;
Graphics.DrawMesh(mesh, matrix, material, gameObject.layer, camera);
}
}
}
}