问题
I am trying to change my script continuously while the Unity game is running after I have entered play mode. I made a procedurally generated mesh and assigned a mesh collider, filter, and a renderer component to the script.
Now I want the mesh to change heights while the game is running. I figure this would be done in the Update
function but I am not sure how I would implement it.
Here's what I got so far:
void Start()
{
mesh = new Mesh();
MeshFilter filter = gameObject.AddComponent<MeshFilter>();
MeshRenderer render = gameObject.AddComponent<MeshRenderer>();
GetComponent<MeshFilter>().mesh = mesh;
GetComponent<Renderer>().material = grassMat;
CreateShape();
UpdateMesh();
}
void UpdateMesh()
{
mesh.Clear();
mesh.vertices = vertices;
mesh.triangles = triangles;
MeshCollider collider = gameObject.AddComponent<MeshCollider>();
mesh.RecalculateNormals();
}
回答1:
Since the example code is not really complete, i´ll point you to some common possible errors:
void Update() is called every frame depending on your framerate, void FixedUpdate() is called every frame on a semi-fixed framerate. If you want something to happen every (fixed) frame, you should place your code in there. In your example you just named your method void UpdateMesh() which does not mean it´s getting called each frame: https://docs.unity3d.com/ScriptReference/MonoBehaviour.FixedUpdate.html
from you posted code it´s not clear, if there are changes happening in void UpdateMesh() at all. For example there is no code which changes positions of vertices.
来源:https://stackoverflow.com/questions/60104136/how-can-i-modify-my-mesh-with-a-c-sharp-script-while-the-game-is-running