Search Unity

Get Texture2DArray from material?

Discussion in 'Shaders' started by jister, Apr 7, 2020.

  1. jister

    jister

    Joined:
    Oct 9, 2009
    Posts:
    1,749
    Is it possible to retrieve a Texture2DArray from a material i C#?

    we can get ColorArray, FloatArray, MatrixArray and VectorArray, any reason why not Texture2DArray?

    Is there any know work around for this?

    thanks.
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,343
    Are you asking why there's no
    GetTexture2DArray
    function? Because GPUs don't support arrays of textures. A
    Texture2DArray
    is a "single texture object" that just happens to have a third dimension, like a
    Texture3D
    . Both of those and
    Texture2D
    use the
    Texture
    class as their parent, and that's what the
    SetTexture
    /
    GetTexture
    functions take. So to get a
    Texture2DArray
    from a material, you just need to call
    GetTexture
    with the appropriate property name.
     
    zwcloud likes this.
  3. jister

    jister

    Joined:
    Oct 9, 2009
    Posts:
    1,749
    @bgolus you are a hero sir!
    for anyone looking to do this here's a small snippet example:

    Code (CSharp):
    1. private void Start()
    2.     {
    3.         Material mat = GetComponent<MeshRenderer>().material;
    4.         texture2DArray = mat.GetTexture("_NameOfArrayInShader") as Texture2DArray;
    5.         for (int i = 0; i < texture2DArray.depth; i++)
    6.         {
    7.             Color32[] pixels = texture2DArray.GetPixels32(i, 0);
    8.             Texture2D texture = new Texture2D(texture2DArray.width, texture2DArray.height);
    9.             texture.SetPixels32(pixels);
    10.             texture.Apply();
    11.             textures.Add(texture); //List of Texture2D
    12.         }
    13.     }
     
    Last edited: Apr 9, 2020