Chainging Texture of a button is not working using C#

I am trying to change the texture of a button like this:

public Texture2D texture2D; static Timer _timer; private String txOutval1;

void Start () {
    txOutval1 = @"Hello";
	texture2D = new Texture2D (200, 200);
	texture2D = Resources.Load("hello", typeof(Texture2D)) as Texture2D;

	_timer = new Timer(2000); // Set up the timer for 2 seconds
	_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
	_timer.Enabled = true;
}

void OnTimedEvent(object source, ElapsedEventArgs e) {
    texture2D = Resources.Load("background", typeof(Texture2D)) as Texture2D;
}

void OnGUI () {
	GUI.Button(new Rect(20,200,400,400),new GUIContent(txOutval1, texture2D));	
}

but the button texture is not at all changing. How can I achieve this?

Unity API is not thread-safe, so even if OnTimedEvent gets called (I’m not sure if Timer works within unity) it wouldn’t work as expected. Also, you don’t need to create a new Texture2D if you are going to load one from the Resources.

You could get similar behaviour using Coroutines or MonoBehaviour.Invoke. For example, you could make Start a coroutine, load the first texture, wait for 2 seconds and load the second.

public Texture2D texture2D;
private String txOutval1;

IEnumerator Start () {
    txOutval1 = @"Hello";
    texture2D = Resources.Load("hello", typeof(Texture2D)) as Texture2D;
 
    yield return new WaitForSeconds(2.0f);
    
    texture2D = Resources.Load("background", typeof(Texture2D)) as Texture2D;

}


void OnGUI () {
    GUI.Button(new Rect(20,200,400,400),new GUIContent(txOutval1, texture2D)); 
}