Hello,
I’m creating a simple 2D plataformer with Unity. In this plataformer I have a GameObject “Player” with a prefab like this:
In short, the player has life, can move and cast fireballs, with each component performing one of the desired behaviours.
However, at some point in the development I decided to remove the player’s ability to cast fireballs. Since I’m using the component based architecture, removing the behaviour was pretty easy from point of view the of GameObject, I just had to remove the “FireBall_Component” component.
However, when taking scripts in consideration, the things started to get messy. In my scripts, there were many GetComponent calls related to the Player’s “FireBall_Component”, and since it was removed, many null reference exceptions started to appear during run time. Many of these exceptions were caused when some script was trying to subscribe to the OnCastFireBall event.
if(go.tag == "Player")
{
go.GetComponent<FireBall_Component>().OnCastFireBall += OnCastFireBall;
}
Since the “FireBall_Component” does not exist any more in the Player GameObject, the GetComponent calls will return null and null reference exceptions will happen. The null reference exceptions problem could be solved with an if statement, checking if the return of GetComponent is null.
FireBall_Component fireBall_ComponentTmp;
if(go.tag == "Player")
{
fireBall_ComponentTmp = go.GetComponent<FireBall_Component>();
if(fireBall_ComponentTmp != null) fireBall_ComponentTmp.OnCastFireBall += OnCastFireBall;
}
But I would still have useless pieces of code all over my scripts. After all, if I’ll never have a “FireBall_Component” in my Player’s GameObject, there is no reason to check if it exists.
This problem has caused me to spend a lot of time executing the game until I was able to find all null reference exceptions and, after that, take a big look at all my code removing the incorrect GetComponent calls.
And this is not the first time I had this problem.
So some questions are:
There is any way to know prior to the game execution if a GameObject has an specific set of components?
There is some way to find any GetComponent calls that will return null before run time?
There is any best practices or desing paterns that I can use to avoid that problem?
This problem has been killing me for quite some time and I would be very thankfull to anyone who can help me.
OBS.: Please apologize any English mistakes. English is not a mother tongue in my country and I’m not used to speaking English in my daily life.