This error message "Not allowed to access vertices on mesh 'MelonSmall' (isReadable is false; Read/Write must be enabled in import settings)" occurs when the mesh does not have the "Read/Write Enabled" option set in the Inspector [1].
Here are the methods to fix the "Not allowed to access vertices on mesh" error in Unity:
Method 1: Enable "Read/Write Enabled" Option in Import Settings
Explanation: This method involves enabling the "Read/Write Enabled" option in the mesh's import settings using the Unity Editor.
Steps:
1. In the Project window, select the mesh asset that is causing the error.
2. In the Inspector window, scroll down to the "Mesh Compression" section.
3. Check the "Read/Write Enabled" option.
4. Re-import the mesh by selecting it in the Project window and choosing "Reimport" from the context menu.
Method 2: Enable "Read/Write Enabled" Option at Runtime
Explanation: This method enables the "Read/Write Enabled" option for the mesh at runtime using code. It is useful to ensure that the mesh is readable in your scripts.
Steps:
1. Use the Mesh.isReadable property to check if the mesh is readable.
2. If it is not readable, create a new readable instance of the mesh, mark it as dynamic (if needed), and assign it to the MeshFilter component.
```csharp
Mesh mesh = GetComponent<MeshFilter>().mesh;
if (!mesh.isReadable) {
// Create a new readable mesh instance
mesh = Instantiate(mesh);
// Mark the mesh as dynamic if needed (e.g., for frequent updates)
mesh.MarkDynamic();
// Assign the readable mesh to the MeshFilter component
GetComponent<MeshFilter>().mesh = mesh;
}
```
In this code:
1. `Mesh mesh = GetComponent<MeshFilter>().mesh;`: This line retrieves the mesh data associated with the GameObject by getting the `MeshFilter` component and accessing its `mesh` property.
2. `if (!mesh.isReadable) {`: It checks if the retrieved mesh is not readable (i.e., you can't access its data directly).
3. `mesh = Instantiate(mesh);`: If the mesh is not readable, a new readable instance of the mesh is created using `Instantiate`. It's a copy of the original mesh and can be modified.
4. `mesh.MarkDynamic();`: This optional line marks the new mesh as dynamic, which can improve performance if you plan to update it frequently
5. `GetComponent<MeshFilter>().mesh = mesh;`: Finally, it replaces the original non-readable mesh with the new readable one, ensuring you can access and modify the mesh data without errors.
Method 3: Convert Mesh to Readable Format at Import Time (Advanced)
Explanation: This method involves changing the mesh's import settings to always convert it to a readable format during import. It is an advanced option for assets you know will be accessed in scripts.
Steps:
1. In the Unity Editor, select the mesh asset.
2. In the Inspector window, under "Mesh Compression," change the "Read/Write" option to "Enabled Always."