Sign in to follow this  
Kk1496

Script Order

Recommended Posts

I have a GameManager that holds a list of sprites. It loads the list using Resources.LoadAll(); Then, I have and objective script that assigns those sprites to image objects.

 

Objective script looks like this:

 

public void SetObjective ()
    {
        int rand = (int)Random.Range (0.0fGameManager.manager.gameItems.Length);
        Debug.Log (GameManager.manager.gameItems[1].name);
        this.GetComponent<Image> ().sprite = GameManager.manager.gameItems[1];
    }

 

This exact same code works to create a grid of sprites. The debug log occurs after the NullRefernceException error, so I changed the script execution order and got the same results. What else can I try changing to get the script to run at a correct time after all of the images have been loaded?

Share this post


Link to post
Share on other sites

Is GameManager a MonoBehaviour?  Is the Resources.LoadAll() call being done in Awake(), OnEnable(), or Start()?  The first two will always run before Start, and are great places to do asset initialization like you're mentioning.

(Also, nitpicky, but your code example there doesn't actually use the rand variable.  I'm assuming this is because you re-typed it for an example, but if not you'll only ever use the second sprite in your loaded sprites list.)

 

 

Edit: I just realized this could be an issue where the GameManager is on a separate object from the SetObjective caller, and I misunderstood the issue.  However, according to this doc, Awake and OnEnable should still run on all the objects in the scene before Start.  Specifically: 

 

Note that for objects added to the scene, the Awake and OnEnable functions for all scripts will be called before Start, Update, etc are called for any of them. Naturally, this cannot be enforced when an object is instantiated during gameplay.

Edited by BCullis

Share this post


Link to post
Share on other sites
Thnx for the help! Simply moving the LoadAll() lime in the game manager to Awake() solved the problem. And yes, I only hard coded the index as a means of debugging the problem. I replaced it after the problem was fixed.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this