I have a quad acting as a background that I want to change its texture to a random texture after a certain amount of time. The script compiles with no errors but when I run the game, it doesn’t work and I get this error:
NullReferenceException: Object reference not set to an instance of an object
(wrapper stelemref) object:stelemref (object,intptr,object)
random_Texture.Start () (at Assets/Scripts/random_Texture.cs:14)
Followed by these errors every second:
NullReferenceException: Object reference not set to an instance of an object
random_Texture.Update () (at Assets/Scripts/random_Texture.cs:31)
Line 14 is where I start assigning values to the Array in the Start() method. I don’t know if I’m assigning the textures to the Array correctly. I moved my planet textures in the Assets/Resources/Planets folder and the script is attached to the background quad.
When I compile the script, I do get this warning though:
Assets/Scripts/random_Texture.cs(8,27): warning CS0649: Field random_Texture._textures' is never assigned to, and will always have its default value
null’
Line 8 would be the private Texture[] _textures; part.
using UnityEngine;
using System.Collections;
public class random_Texture : MonoBehaviour {
private float nextLoad, delayBy = 1f;
private Renderer _renderer;
private Texture[] _textures;
void Start ()
{
_renderer = GetComponent<Renderer>();
_textures[0] = Resources.Load("Planets/planet_1") as Texture;
_textures[1] = Resources.Load("Planets/planet_2") as Texture;
_textures[2] = Resources.Load("Planets/planet_3") as Texture;
_textures[3] = Resources.Load("Planets/planet_4") as Texture;
_textures[4] = Resources.Load("Planets/planet_5") as Texture;
_textures[5] = Resources.Load("Planets/planet_6") as Texture;
}
void Update() {
if(Time.time > nextLoad) {
nextLoad = Time.time + delayBy;
_renderer.material.SetTexture("_MainTex", _textures[Random.Range(0, _textures.Length)]);
}
}
}
I basically want to know how to assign textures to an Array. Also, I would prefer to have all my textures in the Assets/Textures/… folders, but using Resources.Load forces me to put some textures in the Assets/Resources folder.