- Home /
change the mesh of object during runtime using javascript
Hi
how do you change a mesh of an object with javascript during runtime...
it should be as easy as gameObject.Find("myMesh").Mesh="AnotherMesh"; or gameObject.Find("myMesh").MeshFilter.Mesh="AnotherMesh"; or gameObject.Find("myMesh").Renderer.Mesh="AnotherMesh"; you know, something along these lines...
...but its not (by far its not) Every single 'answer' I have seen has not worked? I have tried over 30 of them!
I feel should be astonishingly easy as say hiding an object like...
gameObject.Find("myMesh").Renderer.enabled=false...
I want to do this with javascript not c#
any pointers would be great, thanks community!
Wildikon
Answer by robertbu · Mar 23, 2014 at 06:23 AM
Here is a bit of example code:
#pragma strict
var newMesh : Mesh;
function Start() {
var mf : MeshFilter = GameObject.Find("myMesh").GetComponent(MeshFilter);
if (mf != null) {
mf.mesh = newMesh;
}
}
Note this code assumes that "myMesh" exists and that you are changing and existing mesh. It will fail if "myMesh" does not have a MeshFilter component. It also assumes that your are initializing 'newMesh' by dragging and dropping a mesh onto this variable in the inspector.
Thanks so much, your answer has helped very much!
Here is my scenario, I have a mesh (an fbx I imported made with blender3D) called it original$$anonymous$$esh and dragged into the scene. I put your script onto it (I called it $$anonymous$$eshChange.js), then next to the variable mesh1 I clicked the little circle with black dot and added another mesh (again an fbx) from my meshes folder, and a different mesh for mesh2!
I ran unity and it worked! The original mesh now swaps between mesh1 and mesh2!!
I can do a great deal with this now... Here is my $$anonymous$$eshChange.js script!
#pragma strict
var mesh1 : $$anonymous$$esh;
var mesh2: $$anonymous$$esh;
var mf : $$anonymous$$eshFilter;
var ch:int=0;
function Start()
{
mf = GameObject.Find("original$$anonymous$$esh").GetComponent($$anonymous$$eshFilter);
if (mf != null)
{
mf.mesh = mesh1;
}
change$$anonymous$$esh(ch);
}
//loop between the two meshes - this is just for testing purposes, to see the mesh change in real time!
function change$$anonymous$$esh(ch)
{
Debug.Log("mf="+mf);
if (ch == 0)
{
mf.mesh = mesh2;
ch=1;
}
else if (ch == 1)
{
mf.mesh = mesh1;
ch=0;
}
yield WaitForSeconds(2);
changeAgain(ch);
}
//have to add this beacuse you can't call the a function from within that function - Unity starts throwing its toys out the pram if you ask it to do this! (any ideas on this btw)
//anyway, doing this gets my test done at least, so I live with it!
function changeAgain(ch)
{
change$$anonymous$$esh(ch);
}
thanks again for taking the trouble to answer!
WildIkon