I have an error, script should check for null or not destroy game objects

Hi everyone, I am getting a error message when going from my first scene to my second scene and back to my first scene. If I load my second scene and go to my first scene, there is no error.


The error message reads as follows:


The object of type ‘FieldBackground’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.


My code for the field background is as follows:


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

[RequireComponent (typeof (Image))]
public class FieldBackground : MonoBehaviour {

Image image;

public static Sprite background;

void Awake () {
    image = GetComponent<Image>();
    UIAssistant.onScreenResize += LoadBackground;
}

void OnEnable() {
    LoadBackground();
}

void LoadBackground() {
    if (background != null)
        image.sprite = background;
   
    Texture2D texture = image.sprite.texture;
    float texture_ratio = 1f * texture.width / texture.height;
    float screen_ratio = 1f * Screen.width / Screen.height;

    RectTransform rect = transform as RectTransform;

    if (texture_ratio > screen_ratio) {
        rect.offsetMin = new Vector2(-600, 0);
        rect.offsetMax = new Vector2(600, 0);            
    } else {
        rect.offsetMin = new Vector2(0, -600);
        rect.offsetMax = new Vector2(0, 600);
    }
}

}


Before switching to the scenes, there was no error and now there is, but how do you check to see if this background is null or how do you keep the game objects from being destroyed?

I have had to deal with those. There are a few youtube videos that cover fixing null exception errors, check them out
Fix a Null Reference Exception Error in Unity - YouTube

NullReferenceException: Object reference not set to an instance of an object Unity - YouTube
best of luck, i know errors can be annoying, but they can be fixed

so the gameObject that has this script is being destroyed? It looks like your trying to reference that script but it is gone. You can put a donotdestroyonload in there to prevent that gameObject with script from being destroyed. But I don’t know what the script is on and you may not want it to get passed from scene to scene