Samuel Alonso
Samuel Alonso

Reputation: 33

Unity3D - Programatically adding mesh to empty BoxCollider

😊 I'm looking for some help on the following problem. I'm working with a Unity game, and I've set up a number of invisible walls around certain parts of the environment (to avoid out-of-bounds navigation) which are just a bunch of BoxColliders with no MeshFilter, no MeshRenderer, just empty colliders on their own physics layer for the player to be blocked.

Now, I wanted to add a new feature where I could programatically add a mesh to these empty BoxColliders so that the player can see these now-visible walls and interact with them using their gun, but I ran into the following issue: no matter what I do, I can't get the meshes to show up in-game.

I've scoured multiple Unity forums searching for people with this problem and seems like what is the standard solution is not working for me:

  1. Load up some Mesh to assign later
  2. Give the collider a MeshFilter and assign the mesh. That is, bCollider.gameObject.AddComponent<MeshFilter>().mesh = someMesh;
  3. And give the collider a MeshRenderer and set it to enabled. bCollider.gameObject.AddComponent<MeshRenderer>().enabled = true;

Seems like a very straightforward solution, but it's not working for some reason. I've tried many things already, like procedurally generating a cube mesh just to I can see it pop up, adding a material as well because I thought perhaps the texture was just invisible or something... I don't know, I'm really stumped here. And yes, I understand that in principle I could just add to these colliders a Mesh and MeshRenderer, but I already placed about 700 of these invisible walls and I'd very much prefer not having to go through the editor at all, but doing it all from my C# scripts. Maybe my physics layer is misconfigured and it makes the colliders not appear? Don't know, it really puzzles me why this is happening.

Any and all help will be greatly appreciated! ♥

Upvotes: 0

Views: 304

Answers (1)

KYL3R
KYL3R

Reputation: 4073

Without further detail, I can't explain why it won't show up. Do you add these at runtime? Are they culled or scaled to 0?

Alternative to fix your problem of 700 existing GameObjects: I used the script "Replace With Prefab" from here: https://forum.unity.com/threads/replace-game-object-with-prefab.24311/

It helped me replacing hundreds of GameObjects with Prefabs all at once - just select the objects in hierarchy, drag&drop the desired Prefab into the "wizard" and click "replace". The objects will keep Rotation, Scale etc. So you would just do "GameObject->3D Object->Cube" and have a Mesh with a MeshRenderer. Now make it a Prefab and replace all your Invisible Walls with that. Later changes like adding Scripts to enable/disable the meshRenderer will be easy with a Prefab.

Upvotes: 1

Related Questions