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

C# How can i change the PNG texture in gameObject in runtime

Discussion in 'Scripting' started by N.A.K_FYP, Jan 18, 2014.

  1. N.A.K_FYP

    N.A.K_FYP

    Joined:
    Nov 23, 2013
    Posts:
    21
    Code (csharp):
    1.  
    2. if (GUI.Button(new Rect(20,435,140,70), "PNG texture",guiStyle))
    3.         {
    4.             //Texture2D texture = Resources.Load("Crate.tga") as Texture2D;
    5.             //GameObject.Find("Sphere").transform.renderer.materials.mainTexture[1]=texture;
    6.             //Object[] textures = Resources.LoadAll("Textures", typeof(Texture2D));
    7.              //WWW www = new WWW("http://l.yimg.com/rz/d/yahoo_frontpage_zh-Hant-HK_s_f_p_97.5x56_frontpage.png");
    8.             //yield return www;
    9.             //GameObject.Find("Sphere").transform.renderer.materials[1].mainTexture= www.texture;
    10.                 //var filePath = Application.dataPath + "/Resources/tux.png";
    11.                 //guiText.text = filePath;
    12.                 //if (System.IO.File.Exists(filePath))
    13.                 //{
    14.                    // guiText.text += " EXISTS!!!";
    15.                    // var bytes = System.IO.File.ReadAllBytes(filePath);
    16.                    // var tex = new Texture2D(1, 1);
    17.                   //  tex.LoadImage(bytes);
    18.                   //GameObject.Find("Sphere").transform.renderer.materials[0].mainTexture = tex;
    19.                 //}
    20.                 Object[] textures = Resources.LoadAll("Textures", typeof(Texture2D));
    21.                 Texture2D texture = Resources.Load("UserInterface/Skins") as Texture2D;
    22.                 GameObject.Find("Sphere").transform.renderer.materials[0].mainTexture = texture;
    23.  
    24.         }  
    I have find a lot of method that about how to change the texture(PNG image) into the gameobject, however, i cannot make it work.Anyone can help mt to solve the problem?

    btw, i can change the color of my gameObject during runtime.

    Thanks!
     
  2. caseyboundless

    caseyboundless

    Joined:
    Oct 17, 2011
    Posts:
    590
    All your textures and materials in a file called Resources?
     
  3. N.A.K_FYP

    N.A.K_FYP

    Joined:
    Nov 23, 2013
    Posts:
    21
    Yes, the Skins.png is under Resourse/UserInterface

    however, i cannot change the PNG texture after pressing the button, it only work in change the color, during run it in my android Device