Author Topic: Switching UITexture at run-time  (Read 3072 times)

soofaloofa

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 27
    • View Profile
Switching UITexture at run-time
« on: May 07, 2013, 10:25:10 PM »
Hi,

My goal is to use a different background texture for iPhone4/iPad1&2, iPhone5, and iPad retina. I'm wondering how to change a UITexture to achieve this at run-time. You cannot set the pixel size for UITextures like you can for UIAtlases so I'm curious how it is accomplished.

My current attempt is to query for screen size and then switch the texture but I don't know how this is affected by my UIRoot settings.

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. [RequireComponent(typeof(UITexture))]
  5. public class NGUITextureSwitcher : MonoBehaviour
  6. {
  7.     public UITextureSet[] atlasSets;
  8.  
  9.     private UITexture m_texture;
  10.  
  11.     private void Awake()
  12.     {
  13.         this.m_texture = GetComponent<UITexture>();
  14.     }
  15.  
  16.     private void Start()
  17.     {
  18.         if (atlasSets.Length == 0) return;
  19.  
  20.         UITextureSet set = atlasSets[0];
  21.         for (int i = 0; i < atlasSets.Length; i++)
  22.         {
  23.                         Debug.Log (Screen.height);
  24.             if (Screen.height >= atlasSets[i].triggerHeight)
  25.                 set = atlasSets[i];
  26.         }
  27.         if (set != null)
  28.         {
  29.             if (m_texture.name != set.textureName)
  30.             {
  31.                 if (m_texture.mainTexture != null)
  32.                                 {
  33.                     Resources.UnloadAsset(m_texture.mainTexture);
  34.                                 }
  35.  
  36.                 m_texture.mainTexture = Resources.Load("Backgrounds/" + set.textureName) as Texture2D;
  37.             }
  38.         }
  39.     }
  40. }
  41.  
  42. [System.Serializable]
  43. public class UITextureSet
  44. {
  45.     public string name;
  46.     public int triggerHeight;
  47.     public Vector2 spriteRes;
  48.     public Vector2 textureRes;
  49.     public string textureName;
  50. }
  51.  

Thanks,

Kevin

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: Switching UITexture at run-time
« Reply #1 on: May 08, 2013, 02:16:11 AM »
That's perfectly fine. Don't forget to run MakePixelPerfect on it.