0
\$\begingroup\$

This issue has stumped be for 2 days and I still can't figure it out. I have a leveling script that references and image and subscribes to a global event.

public class LevelSystem : MonoBehaviour
{
    [SerializeField] Image _levelProgressBar;

    void Start()
    {
        GameEvents.OnPickUpExp += AddExp;
    }

    public void AddExp(int amount)
    {
        // Here _levelProgressBar becomes null on random playthroughs
        _levelProgressBar.fillAmount = (float)_experience / _experienceToNextLevel;
    }
}

and an item pickup script that triggers the events before destroying itself

public class ItemPickup : MonoBehaviour
{
    [SerializeField] int amount;

    void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Player"))
        {
            GameEvents.TriggerPickUpExp(amount);
            Destroy(gameObject);
        }
    }
}

Pretty simple stuff. But I can't for the life of me figure out why the image reference becomes null randomly. What I've tried

  • Double check that I didn't have more than one instance of the LevelSystem component
  • Checking that my division never results in a division by zero error
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I've found the issue! Basically I was making use of Unity's 'Enter play mode settings' and disabling the reload domain. Since I was using static events this causes the reference to remain in-between playthroughs. There are two options to fix this:

  • Disable 'Enter play mode settings' in Project Settings/Editor.
  • Unsubscribe to the events in OnDisable.
\$\endgroup\$
1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .