[SyncVar] GameObject Instantiate returns null.

Hi all,

I’m working on converting a local multiplayer game (all players share the same screen) to a networked multiplayer game. This is in Unity 5.2, so it’s using the most up to date stuff.

The issue I’m running into is when I start trying to sync variables across the network.

The way my players currently work is there is an array of GameObjects that contain different space ships (so its random which one they get). When the player spawns, the player’s GameObject ship randomly gets instantiated as one of the space ship GameObjects from the array. Afterward, the ship is given a follow camera component, and a few other odds and ends. It works great locally.

However, I’m immediately running into a problem when I try to sync it over the network. If I try to [SyncVar] the GameObject, the instantiation returns Null. It’s an immediate show stopper and I don’t know how to get around it. I want the ship that the players use to all be synced.

This is a summarized section of the code where I’m running into the problem:

public static class AllShips {
  GameObject[] shipList;
  public static GameObject[] getShipList() {
    if (shipList == null) {
      shipList = new GameObject[10];
    }
    for (int i = 0; i < shipList.Length; i++) {
      shipList *= (GameObject)Resources.Load("Prefabs/Ships/Ship_" + (i + 1), typeof(GameObject));*

}
return shipList;
}
}
public class Player : NetworkBehavior {
[SyncVar] GameObject ship;
void Awake() {
InitState();
}
[Server]
void InitState() {
GameObject[] shipList = AllShips.getShipList ();
int whichShip = Random.Range (0, shipList.Length - 1);
ship = (GameObject)Instantiate (shipList [whichShip]);
ship.name = “Player Ship”;
ship.transform.parent = transform;
Camera cam = ship.AddComponent();

position = new Vector2(
Random.Range (-1000, 1000),
Random.Range (-1000, 1000)
);
ship.transform.position = position;
}
}
As said, all of that works great without the [SyncVar], but as soon as I try to sync it, the Instantiate returns Null instead of a new prefab GameObject. I’m not sure what to do about it or why it’s happening.
FWIW, all of the other components, such as NetworkIdentity, etc. have been added to the player object that spawns.
Ideas?

You can’t SyncVar a GameObject. If you could itd be called SyncGO :slight_smile:

Use SyncVar for basic typed variables only. Instantiate the object on the Server then call Spawn()