Context
I’m trying to make a bit of code for unity 2021 that will generate a readable mesh from a non-readable. I’ve created a function that works sometimes. There are specific meshes in the game that don’t work. Here’s the full function I’m using:
public static Mesh GetReadable(this Mesh mesh)
{
if (mesh.isReadable)
return Object.Instantiate(mesh);
var nMesh = new Mesh();
nMesh.indexFormat = mesh.indexFormat;
// vertices
nMesh.SetVertexBufferParams(mesh.vertexCount, mesh.GetVertexAttributes());
var buffers = mesh.vertexBufferCount;
for (int i = 0; i < buffers; i++)
using (var vBuffer = mesh.GetVertexBuffer(i))
{
var vData = new byte[vBuffer.stride * vBuffer.count];
vBuffer.GetData(vData);
nMesh.SetVertexBufferData(vData, 0, 0, vData.Length, i);
}
// triangles
nMesh.subMeshCount = mesh.subMeshCount;
using (var iBuffer = mesh.GetIndexBuffer())
{
nMesh.SetIndexBufferParams(iBuffer.count, mesh.indexFormat);
var iSize = iBuffer.stride * iBuffer.count;
var iData = new byte[iSize];
iBuffer.GetData(iData);
nMesh.SetIndexBufferData(iData, 0, 0, iSize);
}
// submeshes
var pos = 0u;
for (int i = 0; i < nMesh.subMeshCount; i++)
{
var subMeshIndexCount = mesh.GetIndexCount(i);
nMesh.SetSubMesh(i, new SubMeshDescriptor((int)pos, (int)subMeshIndexCount));
pos += subMeshIndexCount;
}
nMesh.RecalculateBounds();
return nMesh;
}
Problem
When using this function on certain meshes, it would generate a mesh with zero volume, after some debugging I found that the GraphicsBuffer.GetData
function was leaving the array as all zeros, specifically, it wasn’t setting it all to zero, it was leaving it as zeros (if I used a loop to set it all to 1 then it’d still be 1 afterwards). This is occuring in for both the vertex buffers and the index buffers.
I’ve attempted to recreate the problem meshes in a unity project of my own with no luck so I don’t even know what causes these meshes to be like this in the first place.
And before anyone asks, no I cannot just enable isReadable on the meshes because I’m modding the game, not making it, the bundles are already built, I’m not biulding them, I’m just working with the tools I have available.
Edit: In my troubleshooting I’ve also discovered that Instantiating the mesh doesn’t work. When I apply the original mesh to a mesh filter, I can see it, when I instantiate the mesh and put that one the mesh filter instead, it is not visible
Edit 2: As far as I’ve been able to gather online, the buffer not writing any data to the array is caused by the buffer targets not including the Raw
flag. The next problem is that when I add this tag, the vertex buffers still don’t give any data and the index buffer becomes null and throws an error when I try to fetch it (the error just says the buffer is null).
3