'NetworkServer is not active. Cannot spawn objects without an active server in Unity 3D
I am trying to implement a multiplayer feature in Unity3d. Its like a snake game, snake eats food and generate its part. I can successfully generate food and part as well but its not moving and giving me error "NetworkServer is not active. Cannot spawn objects without an active server."
Here is my code :-
private void CmdCheckForFood(Vector3 snakePartPosToBeInitialize,Vector3 headPos)
{
if(_food != null)
{
if (_food.transform.position == headPos) // if food collide with head.
{
_food.transform.position = GenerateRandomPosForFood();
currPartOfSnake += 1;
CmdCreatePartSnake(snakePartPosToBeInitialize);
}
}
}
public void CreatePartSnake(Vector3 snakePartPosToBeInitialize)
{
GameObject obj = Instantiate(snakePart, snakePartPosToBeInitialize, Quaternion.identity) as GameObject;
obj.name = "" + currPartOfSnake;
obj.transform.parent = gameObject.transform;
tail.Add(obj); // tail is list which contain all part of snake
NetworkServer.Spawn(obj);
}
Solution 1:[1]
You're trying to call the NetworkServer on the client side, so in this case CreatePartSnake should be a [COMMAND] in order to run on the Server.
http://docs.unity3d.com/ScriptReference/Networking.CommandAttribute.html
Solution 2:[2]
I dont know if you're still having the issue, but as @Jansen said, you need to add the [Command] tag above the function, and also add Cmd to the beginning of the function.
Also, you can check to see if the server is active by using NetworkServer.active().
something like if(NetworkServer.active()) should suffice in making sure the function isnt called unless the network server is started.
Make sure the your server is actually starting as well!
Solution 3:[3]
Note: Current unity documentation will make you crazy try this at your own risk
I also face the same problem and i resolve it through making the Function with command Attribute, you should need to change your spawning function something like this
[Command]//add command attribute to the spawning function and also add Cmd in function name
public void CmdCreatePartSnake(Vector3 snakePartPosToBeInitialize)
{
GameObject obj = Instantiate(snakePart, snakePartPosToBeInitialize, Quaternion.identity) as GameObject;
obj.name = "" + currPartOfSnake;
obj.transform.parent = gameObject.transform;
tail.Add(obj); // tail is list which contain all part of snake
NetworkServer.Spawn(obj);
}
But first you need to derive your class from Network Behaviour.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jansen |
Solution 2 | Gil Marquez |
Solution 3 | Muhammad Faizan Khan |