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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Can material.mainTexture assignment fail?

Discussion in 'Editor & General Support' started by jules43, Sep 8, 2015.

  1. jules43

    jules43

    Joined:
    Jul 20, 2015
    Posts:
    10
    Apologies if this is in the wrong place, I'm not certain where best to post it.

    I am trying to create a Quad, load a texture into it and display it. The code works fine on PC in editor but displays a white rectangle on Android/GearVR. In the past the code appeared to work but it appears to be fragile.

    Code (csharp):
    1. imageObject = GameObject.CreatePrimitive(PrimitiveType.Quad);
    2. Object.Destroy(imageObject.GetComponent<MeshCollider>());
    3. imageObject.transform.parent = parent.transform;
    4.  
    5. Texture2D imageTexture = new Texture2D(2, 2);
    6. byte[] imageBytes = File.ReadAllBytes(imageFile);
    7. ImageLoaded = imageTexture.LoadImage(imageBytes);
    8.  
    9. Material mat = imageObject.GetComponent<Renderer>().material;
    10. mat.mainTexture = imageTexture;
    11. Shader shd = Shader.Find("Custom/Texture");
    12. mat.shader = shd;
    I have run / stepped through this code and confirmed that: A quad is rendered of the correct size, position and orientation.

    imageTexture is successully created and after LoadImage has the expected width and height (ImageLoaded is true). This info is then used to set the quad size/position, so expected to be correct.

    I note that the image file being loaded is a png, containing an alpha channel and is non-power of 2.

    The shader is found and successfully assigned (it is used fine elsewhere in the scene).

    The only thing that appears not to work is, the assignment of imageTexture to mat.mainTexture. When I put a breakpoint on the line after, it reaches the line but mat.mainTexture is null instead of being the same as imageTexture.

    Can anyone tell me how to debug this further? Or suggest an explanation?

    Thanks
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    The mainTexture property is the same as using SetTexture with _MainTex, so if the shader has no _MainTex, nothing will happen.

    --Eric
     
  3. jules43

    jules43

    Joined:
    Jul 20, 2015
    Posts:
    10
    Thank-you - that explains the problems. It's obvious in retrospect but I don't think I would have spotted it without your help.

    I've switched the order so that I set the shader first and then the texture and all is well.