Search Unity

Same Object, Different Materials

Discussion in 'Scripting' started by marty, Jul 25, 2007.

  1. marty

    marty

    Joined:
    Apr 27, 2005
    Posts:
    1,170
    Is there a way that I can have the same object rendered with one material in one (main) camera and a different material in another (inset) camera?
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Yep, you can use OnPreRender and OnPostRender for that sort of thing. For example:

    Code (csharp):
    1. var whichTag : String;
    2. var material1 : Material;
    3. var material2 : Material;
    4.  
    5. function OnPreRender () {
    6.     var objects = GameObject.FindGameObjectsWithTag(whichTag);
    7.     for (ob in objects) {
    8.         ob.renderer.material = material2;
    9.     }
    10. }
    11.  
    12. function OnPostRender () {
    13.     var objects = GameObject.FindGameObjectsWithTag(whichTag);
    14.     for (ob in objects) {
    15.         ob.renderer.material = material1;
    16.     }
    17. }
    Put that on the inset camera if you want objects with the tag that you define with "whichTag" have "material2" when rendered with the inset camera and "material1" otherwise. Or you could put it on the main camera; doesn't matter really. If it's just one particular object you want to affect, you wouldn't need to bother with tags and loops, of course, and just change the material of that one object instead.

    --Eric
     
  3. AaronC

    AaronC

    Joined:
    Mar 6, 2006
    Posts:
    3,552
    Nice work Eric. ive been doubling up on my geometry and cameras up until now to get this effect. In time I will be keen to try this out. Thanks.
    AaronC
     
  4. marty

    marty

    Joined:
    Apr 27, 2005
    Posts:
    1,170
    Eric5h5, you are an angel sent straight from progammers' heavan. ;-)

    Thanks a gazillion.

    Amazing.

    I just feel the need to say, one more time, how incredibly full-featured and thoughtfully-designed Unity is to support such things.

    Wow.