- Home /
Mesh collider not working as expected
Im trying to detect intersecting gameobjects. I have a simple scene with 4 blocks and a shape. The blocks have box colliders and the shape a mesh collider.
If the shape is intersecting a block it should turn the block red otherwise it should remain blue. For some reason I can't get this to work, it's as if the mesh collider is not accurate enough.
With the image on the left, I would expect the bottom left block to be blue as it's not intersecting the green shape; but it's not. If I drag the shape to the right (right image) the left side blocks turn blue which makes me think the code is working in some form.
Any help would be much appreciated!
Code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class gameController : MonoBehaviour {
public GameObject shape;
public GameObject blockA;
public GameObject blockB;
public GameObject blockC;
public GameObject blockD;
public Material red;
public Material blue;
List<GameObject> blockList;
// Use this for initialization
void Start () {
blockList = new List<GameObject>();
blockList.Add (blockA);
blockList.Add (blockB);
blockList.Add (blockC);
blockList.Add (blockD);
}
// Update is called once per frame
void Update () {
MeshCollider shape_collider = shape.GetComponent<MeshCollider> ();
foreach (GameObject block in blockList) {
BoxCollider block_collider = block.GetComponent<BoxCollider> ();
if (shape_collider.bounds.Intersects (block_collider.bounds)) {
block.GetComponent<Renderer> ().material = red;
} else {
block.GetComponent<Renderer> ().material = blue;
}
}
}
}
Answer by WbrJr · Feb 21, 2018 at 07:22 PM
Hey there,
Do you have "convex" enabled on your meshcollider? If so, turn it of and i think it should work...
have a nice day and good luck
Answer by JedBeryll · Feb 21, 2018 at 08:56 PM
Not exactly a solution but you could make this work with 2 box colliders. Multiple colliders under 1 object works like it's 1 collider. It's better performance-wise too.