- Home /
Materials appear missing at some distances away from the object
I have a script that generates voxel terrain and applies a random material to each cube.
The materials seem to be applied fine, but when any camera (both game camera and scene camera) moves to certain distances away, the objects appear to have no material set. If one camera causes it, it is only visible to that camera
I don't know if this is an error with unity, or with my script.
// create a unit cube and store the mesh from it
GameObject blockMesh = Instantiate(blockPrefab, Vector3.zero, Quaternion.identity);
MeshFilter blockMeshMesh = blockMesh.GetComponent<MeshFilter>();
// add mesh renderer component
MeshRenderer mr = blockMesh.GetComponent<MeshRenderer>();
// move the unit cube to the intended position
blockMesh.transform.position = new Vector3(x, y, z);
chooseMesh = Random.Range(0f, 1000f);
// Randomly decide a material for the cube
// testing for different items with different rarities
if (chooseMesh >= 0f && chooseMesh < 500f)
{
//set material to avoid evil pinkness of missing texture
mr.material = material_1;
}
else if (chooseMesh >= 500f && chooseMesh < 750f)
{
mr.material = material_2;
}
else if (chooseMesh >= 750f && chooseMesh < 875f)
{
mr.material = material_3;
}
else if (chooseMesh >= 875f && chooseMesh < 937.5f)
{
mr.material = material_4;
}
else if (chooseMesh >= 937.5f && chooseMesh < 1000)
{
mr.material = material_5;
}
The camera clipping planes are fine. The object is still rendered, but the material is not. It's not only near and far, materials turn pink briefly at regular intervals.
The code is in a Generate() function, which is called in Start()
I have spent a month trying to solve this and people on StackOverflow keep downvoting or locking my questions without answering them.
It's kind of hard to say without knowing your scene. One thing I will say however is that your last condition isn't quite right. Not only do you not have a default case (which you should), but you check to less than 1000 exclusive, even though 1000 can be an outcome - which would result in no material being set. I would suggest more something like this;
...
else if (choose$$anonymous$$esh >= 875f && choose$$anonymous$$esh < 937.5f)
{
mr.material = material_4;
}
else
{
mr.material = material_5;
}
Your answer
Follow this Question
Related Questions
Render tooltip on top of everything with MRTK 0 Answers
LWRP: Set custom shader at runtime 1 Answer
Rendering objects into another camera with a different material in HDRP 0 Answers
Using a camera replacement shader but keeping the underlying (original) colors? -4 Answers
Best way to swap between view modes 0 Answers