My game freezes randomly, mostly when changing from one level to the next. I cannot tell why this is the case. There are no errors or warnings. This happens when i build the game and when I am testing the game in the Unity editor. It will say unfreeze itself after a few seconds. I have attached one of the level codes and the timer code. I have also attached a picture of how it looks when it freezes. This is one of the level codes :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
public class Arduino5 : MonoBehaviour
{
SerialPort sp = new SerialPort("\\\\.\\COM5", 9600);// Com port and the baud rate of the arduino
Material m_Material;
GameObject Sphere;
void Awake()
{
Sphere = GameObject.FindWithTag("Player");
m_Material = GameObject.FindWithTag("Player").GetComponent<Renderer>().material;
}
void Start()
{
if (!sp.IsOpen)
{ // If the erial port is not open
sp.Open(); // Open
}
sp.ReadTimeout = 250; // Timeout for reading
}
// Update is called once per frame
void Update()
{
if (sp.IsOpen)
{ // Check to see if the serial port is open
try
{
string portreading = sp.ReadLine(); // get the string output of the serial port
float amount = int.Parse(portreading);
if ((amount > 50f) )
{
m_Material.color = Color.grey;
Renderer _rend = Sphere.GetComponent<Renderer>();
Sphere.GetComponent<Renderer>().material = _rend.material;
_rend.material.mainTexture = Resources.Load("face4") as Texture;
}
else
{
m_Material.color = Color.white;
}
}
catch (System.Exception)
{
}
}
}
}
and this is the Timer code:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Timer : MonoBehaviour
{
public int timeLeft = 5;
public Text countdownText;
// Use this for initialization
void Start()
{
StartCoroutine("LoseTime");
}
// Update is called once per frame
void Update()
{
countdownText.text = ("Time Left = " + timeLeft);
if (timeLeft <= 0)
{
StopCoroutine("LoseTime");
countdownText.text = "Times Up!";
Invoke("ChangeLevel", 1.0f);
}
}
IEnumerator LoseTime()
{
while (true)
{
yield return new WaitForSeconds(1);
timeLeft--;
}
}
void ChangeLevel()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
In terms of trying to close the serial port, would something like this work:
void Start()
{ if (!sp.IsOpen) { // If the erial port is not open sp.Open(); // Open sp.ReadTimeout = 250; }
// Timeout for reading
else if (sp != null)
{
{
sp.Close();
}
}
}