I’m GPU-instancing spheres in a scene in a given, editor-determined random area, I want each instance to get a material depending on its Y axis position, but I have no idea how to do that, I already have 5 different materials created for this and assigned on the editor, but I’m just not being able to figure out how to assign the different material to each GPU-instanced object depending on its Y-axis position.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class ObjData
{
public Vector3 pos;
public Vector3 scale;
public Quaternion rot;
public Matrix4x4 matrix
{
get
{
return Matrix4x4.TRS(pos, rot, scale);
}
}
public ObjData(Vector3 pos, Vector3 scale, Quaternion rot)
{
this.pos = pos;
this.scale = scale;
this.rot = rot;
}
}
public class GPU : MonoBehaviour
{
public int instances;
public Vector3 maxPos;
public Mesh objMesh;
public Material Low;
public Material MidLow;
public Material Mid;
public Material MidHigh;
public Material High;
Material PlaceHolder;
private List<List<ObjData>> batches = new List<List<ObjData>>();
// Start is called before the first frame update
void Start()
{
int batchIndexNum = 0;
List<ObjData> currBatch = new List<ObjData>();
for (int i = 0; i < instances; i++)
{
AddObj(currBatch, i);
batchIndexNum++;
if (batchIndexNum >= 1000)
{
batches.Add(currBatch);
currBatch = BuildNewBatch();
batchIndexNum = 0;
}
}
}
// Update is called once per frame
void Update()
{
RenderBatches();
/*foreach (GameObject batchChild in batches)
{
batchChild.transform.position = Vector3.one;
}*/
}
private void AddObj(List<ObjData> batch, int i)
{
Vector3 position = new Vector3(Random.Range(-maxPos.x, maxPos.x), Random.Range(-maxPos.y, maxPos.y), Random.Range(-maxPos.z, maxPos.z));
batch.Add(new ObjData(position, new Vector3(2, 2, 2), Quaternion.identity));
}
private List<ObjData> BuildNewBatch()
{
return new List<ObjData>();
}
private void RenderBatches()
{
foreach (var batch in batches)
{
//HERE IS WHERE I STRUGGLE
/*if (transform.position.y < -7.0f))
{
PlaceHolder = Low;
}
if (transform.position.y >= -7.0f && transform.position.y < -5.0f)
{
PlaceHolder = MidLow;
}
if (transform.position.y >= -5.0f && transform.position.y < 5.0f)
{
PlaceHolder = Mid;
}
if (transform.position.y >= 5.0f && transform.position.y < 7.0f)
{
PlaceHolder = MidHigh;
}
if (transform.position.y >= 7.0f)
{
PlaceHolder = High;
}*/
Graphics.DrawMeshInstanced(objMesh, 0, PlaceHolder, batch.Select((a) => a.matrix).ToList());
}
}
}