0
votes

I am trying to update a sprite using playerprefs and the Dropdown UI Element. Upon selecting Day or night time will determine which sprite is rendered upon the scene restarting/starting. However when I select Day or night it doesn't work. It's not changing the sprite upon load. I have the sprites set in the inspector correctly as-well.

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

public class repeatingBackground : MonoBehaviour {

    private BoxCollider2D groundCollider;
    private float groundHorizontalLength;

    private Sprite spriteRenderer;
    public Sprite daySprite;
    public Sprite nightSprite;

    private int bgImg;

    void Start () {

        bgImg = PlayerPrefs.GetInt ("backgroundImg");
        spriteRenderer = GetComponent<Sprite>(); 
        if (bgImg == 1 || bgImg == 0)
            spriteRenderer = daySprite;
        else if (bgImg == 2)
            spriteRenderer = nightSprite;
        groundCollider = GetComponent<BoxCollider2D> ();
        groundHorizontalLength = groundCollider.size.x;
    }
    // Update is called once per frame
    void Update () {
        if (transform.position.x < -groundHorizontalLength) {
            RepositionBackground ();
        }
    }
    public void OnValueChanged(Dropdown value)
    {
        PlayerPrefs.SetInt ("backgroundImg", value.value);
        PlayerPrefs.Save ();
    }
    private void RepositionBackground()
    {
        Vector2 groundOffset = new Vector2 (groundHorizontalLength * 2f, 0);
        transform.position = (Vector2)transform.position + groundOffset;
    }
}
1

1 Answers

1
votes

If you have an Image component in the hierarchy, you should access the Image component not the sprite, there is no such thing as a 'Sprite' directly attached to the GameObject, it is done either through a SpriteRenderer or an Image.

Try changing this

 spriteRenderer = GetComponent<Sprite>();

To (If you are using an Image)

spriteRenderer = GetComponent<Image>();
if (bgImg == 1 || bgImg == 0)
    spriteRenderer.sprite = daySprite;
else if (bgImg == 2)
    spriteRenderer.sprite = nightSprite;

or (If you are using a SpriteRenderer)

spriteRenderer = GetComponent<SpriteRenderer>();
    if (bgImg == 1 || bgImg == 0)
        spriteRenderer.sprite = daySprite;
    else if (bgImg == 2)
        spriteRenderer.sprite = nightSprite;