- Home /
Changing a Mesh (C#)
I'm trying to have this script load Body
from the top of a Resources
folder and place it on the GameObject
it's attached to.
this.gameObject.GetComponent().mesh = Resources.Load("Body");
But the error I'm getting is:
error CS0266: Cannot implicitly convert type
UnityEngine.Object' to UnityEngine.Mesh'. An explicit conversion exists (are you missing a cast?)
Answer by gjf · Aug 01, 2014 at 03:12 PM
you need to explicitly tell unity the type of resource to load...
either
...Resources.Load<Mesh>("Body");
or
... Resources.Load("Body", typeof(Mesh));
I had tried the typeof
method before and it returned the same error. The `` one removes the error, but then the script stops with no error on play, at that very line.
i added the following code to an empty GameObject
and it loaded a mesh that i had previously saved; i had to add a mesh renderer/material to it in order to see it, but otherwise it worked fine.
public void Awake()
{
var meshComponent = gameObject.AddComponent<$$anonymous$$eshFilter>();
meshComponent.mesh = Resources.Load<$$anonymous$$esh>("Star$$anonymous$$esh");
if (meshComponent.mesh != null)
{
Debug.Log("Loaded " + meshComponent.mesh.name);
}
}
make sure it's actually loading the mesh (needs to be in the root of Resources
can you use a higher res image - that's almost impossible to see the text.
also, what's the file type of your "Body" mesh? looks like you've got something in the $$anonymous$$eshFilter
already called 'GameObject'.
i think i know why you're getting an error - it's because you already have a $$anonymous$$eshFilter
on your game object and my code is trying to add another, which will fail!
change the first line in Awake()
to this
var meshComponent = gameObject.GetComponent<$$anonymous$$eshFilter>() ?? gameObject.AddComponent<$$anonymous$$eshFilter>();
actually DON'T - unity won't like it. it should work, but ...
change to this ins$$anonymous$$d:
var meshComponent = gameObject.GetComponent<$$anonymous$$eshFilter>();
if (meshComponent == null)
{
meshComponent = gameObject.AddComponent<$$anonymous$$eshFilter>();
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613155547im_/https://answers.unity.com/themes/thub/images/avi.jpg)