Combine Mesh Instance 0 is null

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class VehicleCore : MonoBehaviour
{
    [System.Serializable]
    public class VehicleBlueprint
    {
        public List<BuildableData> buildables;
    }
    public VehicleBlueprint blueprint;

    public Rigidbody vehicleBody;

    public Material material;

    private void Start()
    {
        initVehicle();
    }
    private void initVehicle()
    {
        for (int i = 0; i < blueprint.buildables.Count; i++)
        {
            GameObject initBuildable = Instantiate(blueprint.buildables[i].buildableObject, blueprint.buildables[i].pos, vehicleBody.transform.rotation);
            initBuildable.transform.SetParent(transform);
            initBuildable.transform.localEulerAngles = blueprint.buildables[i].rot;
        }
        MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter>();
        CombineInstance[] combine = new CombineInstance[meshFilters.Length];
        int j = 0;
        while (j < meshFilters.Length)
        {
            combine[j].mesh = meshFilters[j].sharedMesh;
            combine[j].transform = meshFilters[j].transform.localToWorldMatrix;
            meshFilters[j].gameObject.SetActive(false);
            j++;
        }
        transform.GetComponent<MeshFilter>().mesh = new Mesh();
        transform.GetComponent<MeshFilter>().mesh.CombineMeshes(combine);
        transform.GetComponent<MeshCollider>().sharedMesh = transform.GetComponent<MeshFilter>().mesh;
        transform.GetComponent<MeshRenderer>().material = material;

        transform.gameObject.SetActive(true);
    }
}

I followed the tutorial here:

Anyone know whats wrong?

The parent (the GameObject you attached your VehicleCore script to) is also put in the meshFilters array. Don’t know why it happens (you only expect to get the MeshFilters from the children with GetComponentsInChildren), but I remember having the same problem a while ago. Simply skip the first entry in the array and you should be good.

2 Likes