Search Unity

Is there a way to use different mesh for different camera within the same GameObject?

Discussion in 'General Graphics' started by AhSai, Jan 18, 2020.

  1. AhSai

    AhSai

    Joined:
    Jun 25, 2017
    Posts:
    129
    Instead of having two separate game objects with different layers and different meshes, is there a way to have only one game object but just replace the mesh for different camera? (similar idea to replacement shader but per object basis for mesh)
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,352
    Nope.
     
  3. mouurusai

    mouurusai

    Joined:
    Dec 2, 2011
    Posts:
    350
    Code (CSharp):
    1. public class Swapmesh : MonoBehaviour
    2. {
    3.     public Mesh mesh0;
    4.     public Mesh mesh1;
    5.  
    6.     public GameObject cam0;
    7.     public GameObject cam1;
    8.  
    9.     private MeshFilter filterP;
    10.  
    11.     // Start is called before the first frame update
    12.     void Awake()
    13.     {
    14.         filterP = GetComponent<MeshFilter>();
    15.     }
    16.  
    17.     private void OnWillRenderObject()
    18.     {
    19.         if (Camera.current.gameObject == cam0)
    20.             filterP.sharedMesh = mesh0;
    21.         else if (Camera.current.gameObject  == cam1)
    22.             filterP.sharedMesh = mesh1;
    23.     }
    24. }
    It's kinda slow but it's works.
     
    bgolus likes this.
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,352
    Wanted to touch on a problem with this particular implementation. OnWillRenderObject() is called after culling, which means if your two meshes have significantly different bounds the object may not display when expected on the edges of the screen or when using occlusion. Basically culling will be done using the bounds of the mesh last set.

    There are lots of ways to swap the mesh via script that'll work, some probably more efficiently. Unless you're rendering a lot of objects you want to be different between the cameras, using two game objects and layers will probably be faster. The other option would be to not use a mesh renderer component at all and use Graphics.DrawMesh or command buffers to draw your objects manually.