There are a few issues in your approach. Firstly, totally unrelated to meshes:
When you do something like this (essentially what you are doing now)
public Vector3 p1 = new Vector3(-1,0,0);
Vector3[] vertices = new Vector3[] { p1 };
p1 = new Vector3(2,2,2);
This doesn’t change the contents of the array for 2 reasons (sort of). First reason is that Vector3 is a struct, not a class, so its passed as a value, not as reference (more on that later).
The other reason this doesn’t work is (lets pretend Vector3 is a ref type): You declare p1 - a reference to a memory address that holds vector (-1,0,0). You put a reference to that address into your array. All fine so far. The last line doesn’t change the data that is stored in your memory address; it assigns p1 to point to a different memory address that holds another vector (2,2,2). Your array still holds a reference to the old address with (-1,0,0).
So in theory this should work better:
Vector3 p1 = new Vector3(-1, 0, 0);
Vector3[] vertices = new Vector3[] { p1 };
p1.x = 2;
p1.y = 2;
p1.z = 2;
Debug.Log(vertices[0]);
Now we are changing the data inside the object the memory address points to - p1 and vecrtices[0] reference the same address so it should work? If you try that, it doesn’t, which is due to the second issue that Vector3 isn’t a reference type.
Because of that, when you put p1 into the array, the array doesn’t get a reference to the original vector but rather gets a copy of the vector that just has the same value(s).
That was basic programming, and a big reason to why the mesh isn’t changing: You aren’t actually changing the vertices because changing p1, p2 and p3 don’t change the contents of the mesh.vertices array.
A third issue is that even is you could change the contents of the mesh.vertices array by changing individual Vectors in it, Unity needs to know the changes so it can pass the new values to the rendering pipeline and eventually make the change visible on your screen.
That’s why, if you want the mesh to change, you need to assign a new array into ‘mesh.vertices’. It’s not an array variable but a property that not only takes in the new array, but also takes the necessary steps to make the changes visible on screen.
The same applies to all the other properties like mesh.normals etc.
So finally, you should do it something like:
Vector3[] vertices = new Vector3[]
{
new Vector3(-1, 0, 0),
new Vector3(0, 2, 0),
new Vector3(1, 0, 0)
};
int[] triangles = new int[]
{
0,1,2
};
Vector3[] normals = new Vector3[]
{
Vector3.forward,
Vector3.forward,
Vector3.forward
};
private MeshFilter mf;
void Start() {
mf = GetComponent<MeshFilter>();
mf.mesh = new Mesh();
mf.mesh.vertices = vertices;
mf.mesh.triangles = triangles;
mf.mesh.normals = normals;
}
void Update() {
if (Input.GetKeyDown("up")) {
mf.mesh.vertices = new[]
{
Random.insideUnitSphere,
Random.insideUnitSphere,
Random.insideUnitSphere
};
Debug.Log("Up is pressed.");
}
}