[CLOSED] Unidentifiable Crash when a script is enabled.

When my WireLevelManager object is enabled, unity just instantly crashes.
Urgently needs advice if possible.

Sorry if this is wrong place.

Edit 1: Problem comes mostlikely from LevelManager, just inheriting from it causes unity to crash
Edit 2: Problem found to be not from Level Manager, instead it comes from my UIManager who listens to event from levelmanager
Edit 3: Ok, this is weird to me now. I discovered the cause for the crash. It occurs when i call base.Start in any subclass of the LevelManager. Any idea? or is this common?
Edit 4: Case closed. Lesson Learned : DONT RUSH STUFF!

** Solution Below **

Ouch, you are doing some crazy bad stuff with properties here. Let me show you

public int score
    {
        get{ return score;}
        set
        {
            score = value;
            if(value > 0)
            {
                if(OnScoreIncreaseEvent != null)
                {
                    OnScoreIncreaseEvent(score);
                }
            }
            else if(value < 0)
            {
                if(OnScoreDecreaseEvent != null)
                {
                    OnScoreDecreaseEvent(score);
                }
            }
        }
    }

When you set score anywhere in code (like you do in your start method) you will cause an endless recursive loop.

score = 10;

this will call the set method of score, which sets the score property, which will call the set method of score, which will set the score property which will call the set property of score.

Get the idea?

You should never, or rarely, set the property itself in its own set method unless you know there is a way for it to be recurse forever. Even then its evil.

So what is happening is, unity is starting your game, runs the Start method:

protected virtual void Start()
    {
        lives = 5;
        timeRemaining = 50.0f;
        score = 50;
        gameState = LevelState.PRE_GAME;
    }

hits the lives = 5 (which has the same issue as score) line and dies in a recursive death fireball and as Unity shares the same thread as the game, your game takes unity with it.

To fix it, you need to have a private variable behind score:

private int mScore;
public int score
    {
        get{ return mScore;}
        set
        {
            mScore = value;
            if(value > 0)
            {
                if(OnScoreIncreaseEvent != null)
                {
                    OnScoreIncreaseEvent(mScore);
                }
            }
            else if(value < 0)
            {
                if(OnScoreDecreaseEvent != null)
                {
                    OnScoreDecreaseEvent(mScore);
                }
            }
        }
    }
1 Like

:sweat_smile: was on a rush… i usually do a private and a public getter and setter. Thanks! will try it

Don’t worry. Happens to everyone. Good luck!