Asynchronous infinite loop

Hi all,

I'm using a c# script (and new to C#) to implement UDP multicast I/O based on a script that was documented in the forums. Below I've pasted the relevant code snippet. The read works great in the simulator, however, when I stop the simulator, the Async receive behavior continues. I thought perhaps I need to insert a check if the simulator is running, but is this this case? Doesn't the script stop execution when the simulator stops?

I thought this might just be an issue in the simulator so I created a build of my test project. Again, it executes just find, but when I quit the application, I get an error message that there was a shutdown error.

What do I need to do in order to appropriately stop and start this read functionality? Is there something like a 'Shutdown' function that mirrors 'Start()' where I can do any necessary cleanup?

Thanks in advance!

void Start () 

   BeginAsyncReceive(); // start receiving data


void UDPSetup(){
    listener = new UdpClient(GroupPort);
    groupEP = new IPEndPoint(GroupAddress, GroupPort);


 // Method to start an Async receive procedure 
private void BeginAsyncReceive() 

    ReceiveOperationInfo objInfo = new ReceiveOperationInfo(); 
    objInfo.objUDPClient = listener; 

    listener.BeginReceive(new AsyncCallback(EndAsyncReceive), objInfo);
// Callback method from the UDPClient, when the async receive procedure received a message 
private void EndAsyncReceive(IAsyncResult objResult) 

    byte[] data = listener.Receive(ref groupEP); 

    // process my data

    //if(EditorApplication.isPlaying) // do I need to have a check here so it won't loop back when I don't want it to?

MonoBehaviour.OnDisable () is called in a number of situations that should cover what you want to do, such as:

  • When the GameObject the script is attached to is destroyed
  • When the game quits (and the object the script is attached to gets destroyed)
  • When the script is removed (using Destroy(Component))
  • When the script is disabled

If you use this approach, you'll probably want to use OnEnable to call BeginAsyncReceive to start it up if you deactivate the script/GameObject during the course of play.