Mesh issues

Hey, I’m getting issues when I try to create a GameObject at runtime and assign it a mesh and all that. The exact error it gives me is; Type UnityEngine.Component does not contain a definition for Mesh and no extension method Meth of any type.

Here is my code;

Debug.Log ("Man spawned");
        GameObject soldier = new GameObject ("Test Soldier");
        Component Body = soldier.AddComponent ("MeshFilter") as MeshFilter;
        soldier.AddComponent ("MeshRenderer");
        Body = soldier.GetComponent ("MeshFilter");
        Body.Mesh = Resources.Load ("cylinder");
        soldier.transform.position = this.transform.position + new Vector3 (0, 0, 2);

I also tried without Body = soldier.GetComponent("MeshFilter");

Change Component Body into MeshRenderer Body.

Don’t use strings in GetComponent, and in C# you have to cast, or use the generic version.

–Eric

Sorry I don’t really know what I’m doing. I’m not much of a programmer. Thanks for all the help, I’ll try these though.

Eric5h5; it says to use string in the API and when I don’t, like in x.addComponent(MeshRenderer) it gives me an error saying invalid arguments. Also changing Component Body to MeshRenderer body only gave me more errors. Same when I changed it to MeshFilter body.

The API specifically says it’s better not to use a string. Unity - Scripting API: GameObject.GetComponent

–Eric

Oh, my mistake. I confused GetComponent with AddComponent.

I’m still getting errors with this.

AddComponent should not use strings either. Stay away from strings, and use the correct types.

–Eric

1 Like

Try it like so:

GameObjectsoldier = newGameObject ("Test Soldier");
MeshFilterBody = soldier.AddComponent<MeshFilter>();
soldier.AddComponent<MeshRenderer>();
Body.mesh = Resources.Load<Mesh> ("cylinder");

I still get errors. Sorry, it’s about there not being a thing defined or whatever. Let me try copying my whole code;

public class Barracks : MonoBehaviour {

    void OnMouseDown()
    {
        SpawnSoldier ();

    }

    void SpawnSoldier()
    {
        Debug.Log ("Man spawned");
        GameObject soldier = new GameObject ("Test Soldier");
        MeshFilter Body = soldier.AddComponent <MeshFilter>();
        soldier.AddComponent ("MeshRenderer");
        // Body.Mesh = Resources.Load ("cylinder");
        Body.Mesh = Resources.Load<Mesh> ("cylinder");
        soldier.transform.position = this.transform.position + new Vector3 (0, 0, 2);
    }



    // Use this for initialization
    void Start () {
        // Debug.Log ("Script started.");
    }
   
    // Update is called once per frame
    void Update () {
   
    }
}

Post the errors as well, please. Also, you are still using AddComponent in the wrong way.

All in all your code is just really weird to me. You should look into Instantiate and Prefabs. They are discussed in the tutorials.