Search Unity

Question Change material texture runtime

Discussion in 'General Graphics' started by xtdiwd, Apr 17, 2021.

  1. xtdiwd

    xtdiwd

    Joined:
    Jul 25, 2020
    Posts:
    135
    I have a Material Mt and a Texture Tx (not Texture2D)
    How do I change the maintexture of the Mt with Tx?

    Mt.texture=Tx; does not have effect
    SetTexture make error.
     
  2. Omniglitch

    Omniglitch

    Joined:
    May 29, 2017
    Posts:
    37
    The correct use of SetTexture is described in this page of the Unity documentation: https://docs.unity3d.com/ScriptReference/Material.SetTexture.html

    A simplification of their example would be:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class Example : MonoBehaviour {
    4.  
    5.     public Texture mainTexture;  // Set this texture in the inspector
    6.  
    7.     void Start ()
    8.     {
    9.             GetComponent<Renderer>().material.SetTexture("_MainTex", mainTexture);
    10.     }
    11. }
    If you're still getting an error doing it this way, show us the error and the code you're using, so we can see what might be going wrong.
     
  3. xtdiwd

    xtdiwd

    Joined:
    Jul 25, 2020
    Posts:
    135
    Tx is read from disk and I want to assign it to Skybox.

    My code is currently

    Code (CSharp):
    1. Texture Tx;
    2.  
    3. // Reading from disk
    4.  
    5. RenderSettings.skybox.SetTexture("_Tex",Tx);
    Error:
    Error assigning 2D texture to CUBE texture property '_Tex': Dimensions must match
    UnityEngine.Material:SetTexture (string,UnityEngine.Texture)

    at the line RenderSettings.skybox.SetTexture("_Tex",Tx)

    Also my skybox, and its Material in the Assets become white.

    This happens even if I load the original image of the material.



    Instead if I use

    Code (CSharp):
    1. Texture Tx;
    2.  
    3. // Reading from disk
    4.  
    5. RenderSettings.skybox.SetTexture("_MainTex",Tx);
    I have no error but nothing happens
     
    Last edited: Apr 19, 2021
  4. lilacsky824

    lilacsky824

    Joined:
    May 19, 2018
    Posts:
    171
    So you Texture that you want assign is Cubemap?
     
  5. xtdiwd

    xtdiwd

    Joined:
    Jul 25, 2020
    Posts:
    135
    The texture originally assigned has TextureShape=Cube. The one I want to assign probably no: I load it with UnityWebRequest, get a Texture object.
    At this point I suppose I should set TextureShape=Cube in the new one too, but I failed.
    I've read examples online that use TextureImporter which is part of UnityEditor though, so it wouldn't work compiled.

    Actually I noticed that UnityWebRequest returns a Texture2D but I assign it in a Texture.