Search code examples
c#unity-game-enginesprite

Unity: Sprite not changing after condition is satisfied


First time using Unity and C#. Created a button that would just count up to a certain value, after that value was reached, it would change an image.

My image is a Texture2D which I tried converting to a sprite, but it would always throw an object reference not set to an instance of an object, even though the sprite isn't null and I'm unsure of object it could be referring to.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class testButton : MonoBehaviour
{
//test function for testing onClick()
public void Test(){
  counter++;
  if (counter \> 10){
    IconManager.instance.changeImage();
  }
 }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class icon : MonoBehaviour
{
public Texture2D[] iconTextures;
public Texture2D tester;
public Sprite newSprite;
public Image newImage;

    public static icon instance;
    
    public void changeImage(){
        tester = iconTextures[1];
        newSprite = Sprite.Create(iconTextures[1], new Rect(0, 0, tester.width, tester.height), new Vector2(0.5f, 0.5f), 100.0f);
        gameObject.GetComponent<Image>().sprite = newSprite;
    }

}

Any help would be great because I'm out of ideas. thanks

I tried a lot of tutorials and articles and it appeared we had the same style of code but mine always threw the exception.


Solution

  • I was able to fix this issue. Basically what I did was, instead of trying to convert to a sprite or anything, I used it as a raw image.

    I added a Raw Image component to that image, set the default texture and in the associated script, my code looked like this:

    public class Icon : MonoBehaviour
    {
    public Texture2D[] iconTextures;
    public Texture2D tester;
    private int counter = 0;
    
    public static Icon instance;
    
    private void Awake(){
        instance = this;
    }
    
    public void incrementCounter(){
        counter++;
    }
    
    public int getCounter(){
        return counter;
    }
    
    public void changeImage(){
        tester = iconTextures[counter];
        if (getCounter() != 4){
            incrementCounter();
        }
        instance.gameObject.GetComponentInChildren<RawImage>().texture = tester;
    }
    }