- Home /
Unity crashes on GameObject = hit.collider.gameObject;
Hi everyone.
I'm trying to store a raycast-hitted game object in a variable, so I can change the material of it later on. At the moment, Unity crashes every time it runs this particular line of code, the line that says:
selectedUnit = hit.collider.gameObject;
Here is the code:
public class SelectUnit : MonoBehaviour {
private Ray ray;
private RaycastHit hit;
public GameObject selectedUnit;
void Update () {
int i = 0;
while (i < Input.touchCount) {
if (Input.GetTouch(i).phase == TouchPhase.Began) {
ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
if (Physics.Raycast(ray, out hit, 100)) {
selectedUnit = hit.collider.gameObject;
Debug.Log ("selected unit is: " + selectedUnit.name);
}
++i;
}
}
}
}
If i omit that line of code with //, the project runs fine, but if it's run, then Unity will crash. Can anybody work out why it crashes?
I went through and removed as many debug.log's as I could find, so I could see if it came up with something in the editor's console. Nothing there... but now it does bring up a small error window:
"Fatal error in gc" "Too many heap sections"
...with an O$$anonymous$$ button to click, which then shuts down Unity.
Answer by whydoidoit · Jun 06, 2012 at 04:43 PM
Looks to me like your i++ in the while loop is inside the wrong bracket and you are not incrementing unless one of the touches is in the Began phase. Could therefore be an infinite loop.
I didn't have a chance to test it until just now, but your solution seems to have fixed it.
Thanks $$anonymous$$ike :)