Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Unity 2022.2 is now available as the latest Tech release.
    Dismiss Notice
  3. We are making some changes to the DOTS forums.
    Dismiss Notice
  4. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice

How to instantiate the same object with different textures?

Discussion in 'Scripting' started by RayDawg, Sep 17, 2014.

  1. RayDawg

    RayDawg

    Joined:
    Mar 19, 2013
    Posts:
    108
    I want to be able to instantiate an object multiple times but with different textures. Currently, I have a script that has a GameObject variable and a gameobject is attached to said variable. In the script, I also have an array of different textures I would like to apply to said gameobject. This is what I'm currently using in C#:

    Code (CSharp):
    1. if(x == 1)
    2. {
    3.      ChangingObject.renderer.material.mainTexture = TextureArray[0];
    4. }
    5. if(x == 2)
    6. {
    7.      ChangingObject.renderer.material.mainTexture = TextureArray[1];
    8. }
    9.  
    10. // Line of code to instantiate gameobject goes here ______________
    11.  
    Can anyone point me in the right direction or point out what I (most likely) did wrong?
     
  2. image28

    image28

    Joined:
    Jul 17, 2013
    Posts:
    457
    Try changing the material after the gameobject is instantiated.... see if that helps
     
  3. RayDawg

    RayDawg

    Joined:
    Mar 19, 2013
    Posts:
    108
    It did nothing except cause the first object that was instantiated to have no texture.

    Edit: I did this by taking the line of code that instantiated the object and moving it above the if statements.
     
  4. cmcpasserby

    cmcpasserby

    Joined:
    Jul 18, 2014
    Posts:
    315
    when you instantiate a object, it will return reference to that object for you, which you can use to access the renderer component and set a new material.a

    Code (CSharp):
    1.                 GameObject myObj = (GameObject)Instantiate(myPrefab);
    2.                 myObj.renderer.material = myNewMat;
    3.  
     
    nasym909 likes this.
  5. RayDawg

    RayDawg

    Joined:
    Mar 19, 2013
    Posts:
    108
    It worked, thanks!