How can I modify my mesh with a C# script while the game is running

狂风中的少年 提交于 2020-03-06 09:26:51

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!