[Command] vs Coroutines

Hi!

I’m working on a multiplayer videogame and one of my scripts pseudo-code looks like:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class DoStuff : NetworkBehaviour
{
   
    // Update is called once per frame
    void Update()
    {
        //Only usable on client-side
        if (!isServer) {
            return;
        }
        else {
            if (Input.GetMouseButtonDown(0))
            {
                StartCoroutine(CmdCoroutine());
            }
        }

    }

    //Called on client-side but executed on Server to inform all the clients
    [Command]
    IEnumerator CmdCoroutine()
    {
        while (condition)
        {
            //doStuff
            yield return new WaitForSeconds(0);
        }
    }
   
}

As you can see, I want that when client click his mouse start a coroutine on the server using the “[Command]” syntax, so other clients can saw the “stuff” the client has done.

My problem is that unity debug says
“Command Function cannot be a coroutine”

Then my question is:
How can I skip this kind of behaviour?
I really need to do my stuff on a coroutine started by client, and the things he made, have to be seen by the rest.

Thanks for your time and point of view!

Oo

You can’t do that. You have to understand that command will be played on server. You can’t ever return something (IEnumerator is something).

What you want is just a command that start a coroutine ?

So do it :

    void CmdCoroutine()
    {
       StartCoroutine(ServerCoroutine());
    }

IEnumetor ServerCoroutine()
{
while(condition)
{
//Do stuff
yield return new WaitForSeconds(0); //Change this by yield return null. it's better
}

And command function are not called on client like you comment suggest. It’s only called on server side.

With command you just tell server : “Play this function on your side” that’s why you can’t return something. It’s just information, you just send information, no function are called client side, client just send information to server to call a specific function on server. that’s all :slight_smile:

1 Like

Thanks for that point of view and the tips (like the null return) Driiade.

Maybe my idea of what I really want to achieve is wrong, cause this solution do not affect to my real problem.

But it solves what I specify on the post so many thanks anyways!