Search Unity

[SOLVED] Assigning textures to multi materials with script

Discussion in 'Formats & External Tools' started by Vimalakirti, Jan 25, 2010.

  1. Vimalakirti

    Vimalakirti

    Joined:
    Oct 12, 2009
    Posts:
    755
    I have a single object created with sub materials in Max. It imported fine with texture names intact. It's a book, so the names are "binding," "front cover," etc, but I'm not sure if that matters or if each one has a number hidden somewhere.

    How do I assign materials to these sub (multi) materials with scripting? One idea I saw on the forums was this:

    Code (csharp):
    1.     var themats = renderer.material;
    2.     themats[i] = newTex;
    3.     renderer.materials = themats;
    But that's not compiling.
    Any ideas?

    Thanks.
     
  2. Vimalakirti

    Vimalakirti

    Joined:
    Oct 12, 2009
    Posts:
    755
    Here's a screenshot of the inspector window. Now I see where each material has a number ID, but I still don't know what to dooooooo...
     

    Attached Files:

  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    You need to add an "s" on the end of your first line of code.

    --Eric
     
  4. Vimalakirti

    Vimalakirti

    Joined:
    Oct 12, 2009
    Posts:
    755
    After groaning for five minutes at the simplicity of your response, I wrote this to try it out:

    Code (csharp):
    1. public var newTex : Texture ;
    2.  
    3. function Awake(){
    4.    var themats = renderer.materials;
    5.    var i = 1;
    6.    themats[i] = newTex;
    7.    renderer.materials = themats;
    Wanting to just plug a texture in there in the inspector (before trying to figure out how to load it with the script... one step at a time here...) BUT it gave me this error:

    Assets/Scripts/Books/BookOneScript.js(9,17): BCE0022: Cannot convert 'UnityEngine.Texture' to 'UnityEngine.Material'.

    referring to the line "themats = newTex;"

    Of course I don't know the subtlety here. If it wouldn't be too much trouble, Eric, you're always so helpful and I know you're busy. But while you're here, if you could phrase your answer by giving me the texture version of the function

    var myObject = GameObject.Find("object");

    var newTex = Texture.Find("texture");

    With my undying love and devotion,
    Vimalakirti
     
  5. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    That means you're trying to assign a texture as a material, but you can only assign a texture to the texture property of a material.

    Code (csharp):
    1. themats[i].mainTexture = newTex;
    --Eric
     
  6. Vimalakirti

    Vimalakirti

    Joined:
    Oct 12, 2009
    Posts:
    755
    Bingo.


    Thanks again for all your help, Eric!