- Home /
Get Component or Check if Null SoftLocks Game (C#)
I am creating a random dungeon generator, and have this method that finds the child of spawned "Room" object that has the "Wall" tag, and then gets the TileMapCollider2D component from it.
I am unsure why, but this freezes Unity, forcing me to Force Quit it.
I think I have pin-pointed the problem to when I try to assign the found TileMapCollider2D to a variable ("col"). Edit: The problem does not only lie in the assignment. It may also be in checking if it is null. Here is the script:
void CheckRoomOverlap(GameObject room) {
TilemapCollider2D col = null;
Debug.Log ("We're entering the foreach loop!");
foreach (Transform child in room.transform) {
Debug.Log (child.name + " is being taken in for questioning!");
if (child.tag == "Wall") {
Debug.Log ("Found a dead end captain. Wait... this is a clue!");
if (child.gameObject.GetComponent<TilemapCollider2D> () != null) {
Debug.Log ("Is this where the problem is?");
col = child.gameObject.GetComponent<TilemapCollider2D> ();
break;
} else {
Debug.LogError ("There is no TileMapCollider attached to an object tagged as \"Wall\"");
}
}
}
if (col == null) {
Debug.LogError ("Could not find TileMap on Wall child of room");
}
(There is more after, but it does not seem to be the source of the problem)
I don't see any problems with this method and the col = child.gameObject.GetComponent (); line. Pretty much the biggest reason to such freezes is infinite loop. Are you 100% sure this line causes the freeze?
@NoDumbQuestion This specific loop seems to be the source of the problem. The script did not freeze the game when I commented it out.
@donutLaserDev When I commented out the section of this foreach loop, the game did not freeze. And it did not freeze before, until I added this. But... it may be possible that I keep calling the "TrySpawnRoom" method too many times. I'll look into that actually. Never thought of that...
Answer by foureyes44 · Jun 02, 2018 at 01:21 AM
Okay... turns out there was an infinite loop, in the form of me calling the TrySpawnRoom method over and over (not shown here). That was kind of stupid of me.
Your answer
Follow this Question
Related Questions
GetComponent keeps returning null 3 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Unity freezes after invoking method in loop of the same method (C#) 0 Answers
How do i refer to a linerenderer attached to my object? 2 Answers