Search Unity

Loading Image To PNG at runtime CODE

Discussion in 'Scripting' started by pan-master, Mar 22, 2019.

  1. pan-master

    pan-master

    Joined:
    Nov 11, 2013
    Posts:
    127
    Code (CSharp):
    1. public class overrideTexture : MonoBehaviour
    2. {
    3.     public static Texture2D tex;
    4.     Renderer renderer;
    5.     WWW www;
    6.  
    7.  
    8.      IEnumerator Start()
    9.     {
    10.         tex = new Texture2D(4, 4, TextureFormat.DXT1, false);
    11.         using (www = new WWW(Application.dataPath +"/Floor.png"))
    12.         { yield return www;
    13.             www.LoadImageIntoTexture(tex);
    14.             renderer.material.mainTexture = tex;
    15.         }
    16.  
    17.     }
    18.  
    19. }

    I tried to make it work in many ways but still
    NullReferenceException: Object reference not set to an instance of an object
    overrideTexture+<Start>d__3.MoveNext () (at Assets/KF Files/KF Scripts/overrideTexture.cs:18)

    it looks lie (www = new WWW(Application.dataPath +"/Floor.png")
    does not read from Assets folder, I bet Iam missing something
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Don't use datapath. If you don't want to tie in through a variable, put the images in
    StreamingAssets

    And use Application.StreamingAssets to access it
     
  3. Laperen

    Laperen

    Joined:
    Feb 1, 2016
    Posts:
    1,065
    You could try yielding the LoadImageIntoTexture aswell, maybe the Texture2D wasnt ready before being applied.