I’m doing a multiplayer FPS in Unity5, and I have this code to move the local player:
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class PlayerController : NetworkBehaviour
{
public GameObject bulletPrefab;
public Transform bulletSpawn;
public int fireLocked;
void Start(){
fireLocked = 0;
}
void FixedUpdate()
{
if (!isLocalPlayer)
{
return;
}
var x = Input.GetAxis("Horizontal") * Time.deltaTime * 3.0f;
var z = Input.GetAxis("Vertical") * Time.deltaTime * 3.0f;
if (Input.GetKeyDown("space")){
this.GetComponent<Rigidbody>().AddForce(new Vector3(0f,10f,0f));
}
transform.Translate(x, 0, z);
transform.Rotate (new Vector3 (0.0f,Input.GetAxis ("Mouse X")*5.0f,0.0f));
if (Input.GetMouseButtonDown(0))
{
if (fireLocked==0) {
Debug.Log ("fired");
CmdFire ();
}
}
}
// This [Command] code is called on the Client …
// … but it is run on the Server!
[Command]
void CmdFire()
{
// Create the Bullet from the Bullet Prefab
var bullet = (GameObject)Instantiate (
bulletPrefab,
bulletSpawn.position,
bulletSpawn.rotation);
// Add velocity to the bullet
bullet.GetComponent<Rigidbody> ().velocity = bullet.transform.forward * 6;
// Spawn the bullet on the Clients
NetworkServer.Spawn (bullet);
// Destroy the bullet after 2 seconds
Destroy (bullet, 2.0f);
}
public override void OnStartLocalPlayer ()
{
if (isLocalPlayer) {
FindObjectOfType<Camera> ().gameObject.transform.position = this.transform.position+new Vector3(0f,0.5f,0f);
FindObjectOfType<Camera>().gameObject.transform.SetParent (this.transform);
}
}
public void LockFire(){
bLockFire ();
}
public void UnLockFire(){
bUnLockFire ();
}
void bLockFire(){
fireLocked = 1;
Debug.Log (fireLocked);
}
void bUnLockFire(){
fireLocked = 0;
Debug.Log (fireLocked);
}
}
Other class (named Shop) calls the LockFire void. That void is supposed to change fireLocked to 1, and it does, but later, in the FixedUpdate void, fireLocked is 0.
I have debugged, and the results show up that fireLocked changes to 1 in the LockFire void, but it doesn’t in the FixedUpdate void.
Even if I do player.GetComponent ().fireLocked = 1; from the Shop script, it doesn’t seem to work.
Also, UnLockFire ISN’T called.
Why is this? How do I change the fireLocked variable too in the FixedUpdate void?
P.S: The value of fireL NEVER changes from zero in the FixedUpdate void, and, if you change FixedUpdate() to LateUpdate, it’s the opposite: It never changes from 1 for no reason, althrough LockFire() hasn’t been called…
EDIT: Now it works! I’ve replaced FixedUpdate() to LateUpdate() And then I switched back to FixedUpdate(), and it worked! I think it was an Unity problem?
But later, I removed the Lockfire voids, because I was changing FireL directly with player.GetComponent ().fireLocked = 1. Then, it didn’t work. Whaaaaat?
This is an unity3d problem for sure.