0

I am trying to create a singleton that downloads textures from the web. but whenever I pass URL to singleton through the external script I get an error saying an object is not set to Instance of an object at line below:

WebImage.instance.url = imageURL;

Below is an implementation of the singleton.

public static WebImage instance;

[SerializeField] public string url;

[SerializeField] public Texture2D texture;

private void Awake()
{
    if (instance != null)
    {

        Destroy(this.gameObject);
        return;
    }
    instance = this;
    DontDestroyOnLoad(this.gameObject);
}

Below is an implementation of another GetImage script in which I am sending the URL to the above singleton.

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

public class GetImage : MonoBehaviour
{
    [SerializeField] List<Texture2D> Textures;
    [SerializeField] public string imageURL = "https://arqosh.s3.ap-south-1.amazonaws.com/images/0.5046188924886419-images%20(1).jfif";
    [SerializeField] Texture2D texture;

    void Awake()
    {
        **WebImage.instance.url = imageURL;**  // error here saying object is not set to an instance of object.
        texture = WebImage.instance.texture;
    }
}
Geeky Quentin
  • 2,469
  • 2
  • 7
  • 28
Omkar P
  • 29
  • 5
  • 5
    Maybe the latter Awake is executed before the singleton, so the instance is not created yet. Perhaps you can use Start in GetImage instead? Start is always after all Awakes have been executed. https://docs.unity3d.com/Manual/ExecutionOrder.html – antont Sep 14 '22 at 18:30

1 Answers1

1

Both assigning a singleton reference and accessing singleton reference written on Awake. So you are accessing singleton reference before initialising it. Placing access code in Start will solve the problem.

Alternatively you can also set Script Execution Order in Edit->Project Settings->Script Execution Order