I’ve seen the examples provided by Unity, but I must be missing something because I’m not getting the results I expect.
In my initial test, I’m simply trying to draw a non-moving, user defined mesh, with a user defined material. (New scene, new project). Unfortunately, while I can get the mesh to show up on camera, it looks like it has no lighting on it, as it’s completely black. (Lighting not applied is confirmed; tested using unlit shader materials, which DO show up properly.)
The main question is: how do I fix this script to allow the material to show up properly, with lighting?
(Note on script: it is necessary to add (but not configure) a renderer component, in order for OnWillRenderObject to be executed. I used a meshRenderer, without a meshfilter. Can this be avoided, if I want to move the mesh?)
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
[ExecuteInEditMode]
public class AllCameraCommandRender : MonoBehaviour
{
List<int> assignedCameraGUIDs;
public Mesh meshToRender;
public Material matierialForMesh;
CommandBuffer cb;
private void Start()
{
if (assignedCameraGUIDs == null) assignedCameraGUIDs = new List<int>();
else assignedCameraGUIDs.Clear();
}
public void OnWillRenderObject()
{
if (assignedCameraGUIDs == null) assignedCameraGUIDs = new List<int>();
Camera cam= Camera.current;
int id = cam.gameObject.GetInstanceID();
if (!assignedCameraGUIDs.Contains(id))
{
if (cb == null)
{
Matrix4x4 M = transform.localToWorldMatrix;
//Matrix4x4 V = cam.worldToCameraMatrix;
//Matrix4x4 P = GL.GetGPUProjectionMatrix(cam.projectionMatrix, false);
//Matrix4x4 I = Matrix4x4.identity;
cb = new CommandBuffer();
// cb.SetRenderTarget(BuiltinRenderTextureType.CameraTarget);
cb.DrawMesh(meshToRender, M, matierialForMesh);
}
cam.AddCommandBuffer(CameraEvent.BeforeForwardOpaque, cb);
// cam.AddCommandBuffer(CameraEvent.BeforeLighting, cb);
assignedCameraGUIDs.Add(id);
}
}
}
I was also experimenting with changing the CameraEvent: I tried to use BeforeLighting, like the decals example does, but this change prevented the object from being visible at all. Why is that? (I saw a post in the forum indicating that CameraEvent might be using the matrix differently, so I experimented with some variants: none, except the transform.localToWorldMatrix, seemed to work- but thats why they are in the code above.)
I also tried using the SetRenderTarget command, but this seemed to have no effect. I assume that if I make no changes to the target, the default render target will be the BuiltinRenderTextureType.CameraTarget. Is that correct?