Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    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!