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

Change background texture from an array of textures held in a singleton

Discussion in 'Scripting' started by TxAg03, Jun 13, 2015.

  1. TxAg03

    TxAg03

    Joined:
    May 20, 2015
    Posts:
    21
    I've created a singleton of an ApplicationModel class to hold various info that will be used across scenes. I have created an array of Textures for possible different backgrounds that I would like to select at random. Problem I am having is when I select a Texture at random and save that to a variable in the singleton, I keep getting a null reference when I try to apply that texture to my background plane.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class ApplicationModel : MonoBehaviour
    5. {
    6.     public static ApplicationModel appModel;
    7.    
    8.     public Texture[] backgroundTextures;
    9.     public Texture _backgroundTexture;
    10.    
    11.     void Start()
    12.     {
    13.         _backgroundTexture = backgroundTextures[Random.Range(0, backgroundTextures.Length)];
    14.     }
    15. }
    Then when I try to reference _backgroundTexture on my background plane, it gives me a null reference.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class BackgroundController : MonoBehaviour
    5. {  
    6.     void Start ()
    7.     {
    8.         //this.GetComponent<Renderer>().material.mainTexture = ApplicationModel.appModel._backgroundTexture;        // DOES NOT WORK      
    9.  
    10.         this.GetComponent<Renderer>().material.mainTexture = ApplicationModel.appModel.backgroundTextures[Random.Range(0, ApplicationModel.appModel.backgroundTextures.Length)];    // WORKS      
    11.     }
    12. }
    It works if I reference the Texture array with a random index, but does not work when I reference the Texture variable I set in Start().

    How can I set up a variable inside my ApplicationModel to hold a single Texture from my Textures array that I can use throughout my scenes? I have gotten the above to work by creating a random index and instead of referencing the random Texture, I reference the Textures array at the random index. Is there a way to set the Texture variable that I can reference vs using an index?

    Thank you.
     
  2. TxAg03

    TxAg03

    Joined:
    May 20, 2015
    Posts:
    21
    Not sure why this worked, but I used gameObject.GetComponent... vs this.GetComponent... and all seems to be working.