Search code examples
unity-game-engineunity3d-unet

GameObject Rotation does not happen on Client Side


Flip a 2d GameObject and place it on exact the same position works well on both sides. Rotating 2d GameObject works well on both sides

However, if i flip the GameObject, by executing Cmd_DoTheSpawn, the rotation is not reflected on the "other" client.

I would need help to get this work.

Here is the code I use:

[Command]
void Cmd_DoTheSpawn(GameObject myGameObject) {

    // Check if front or back?
    char lastChar = myGameObject.tag[myGameObject.tag.Length - 1];

    if (lastChar == 'B') {
        convertedObjectTag = unet_Back2Front [myGameObject.tag];
    } else {
        convertedObjectTag = unet_Front2Back [myGameObject.tag];
    }

    GameObject my1 = Resources.Load (convertedObjectTag) as GameObject;

    float z = myGameObject.transform.localEulerAngles.z;

    //var go = (GameObject)Instantiate (my1, myGameObject.transform.position, myGameObject.transform.localRotation);
    var go = (GameObject)Instantiate(my1, myGameObject.transform.position, Quaternion.Euler(0f, 0f, z));
    go.name = go.name.Remove(go.name.Length - 7); // Remove the '(Clone)' in name

    NetworkServer.SpawnWithClientAuthority(go, base.connectionToClient);

    print ("myGameObject: " + myGameObject.transform.position);

    if (myGameObject == null)
        print ("myGameObject NULL" + myGameObject.transform.position);

    Rpc_DoTheRot (go, myGameObject);

    myNetID = myGameObject.GetComponent<NetworkIdentity> ();
    Cmd_DestroyGameObject (myNetID.netId);
}

Thanks to @LumbusterTick i did get it to work, meaning the rotation is ok. However, i did get another problem that i do not fully understand.

I added the following code:

[ClientRpc]
public void Rpc_DoTheRot(GameObject newGO, GameObject oldGO) {
    print ("Rpc_DoTheRot");

    if (newGO == null)
        print ("newGO NULL");
    if (oldGO == null)
        print ("oldGO NULL");

    newGO.transform.rotation = oldGO.transform.rotation;
}

...which i call after spawn but prior to destroy, see updated code above.

It does place the flipped prefab in correct rotation but i do get the following messages:

oldGO NULL

as well as:

NullReferenceException: Object reference not set to an instance of an object

I know perfectly well what that means but not why it happen as all values of the myGameObject is nulled when i send them. ...and i do it prior to destroy.

I do not understand why it is null but still effect the rotation on the new object.


Solution

  • From you command function after you network spawn call a clientrpc function and pass instantiated gameobject to it and change its rotation there.