When using a variable that is declared outside of the spawn()/sleep(), you need to check it isn't null before using it. This is a major cause for runtimes.