- Home /
NullReferenceException on Photon Unity RPC Call
Hey guys, been trying to figure this out for way to long and it's starting to get me down.
I'm working on a multiplayer game where the players can join at any time and take turns in stages. Here's what I believe is the offending code:
void OnJoinedRoom(){
myPlayerNumber = (int)PhotonNetwork.playerList.Length;
xPos = (float)PhotonNetwork.playerList.Length * 0.2f;
player = PhotonNetwork.Instantiate("Prefabs/Knight", new Vector3(-0.2f - xPos, -0.81f, 0),
Quaternion.identity, 0);
// game logic: if this is the only player, it's our turn
if (PhotonNetwork.playerList.Length == 1){
playerWhosTurnItIs = PhotonNetwork.player.ID;
meanCrab = PhotonNetwork.Instantiate("Prefabs/EnemyMeanCrab", new Vector3(1.2f, -0.61f, 0),
Quaternion.identity, 0);
}
}
When it's the player's turn they are allowed to press a button and attack the spawned enemy. The following function is called within a coroutine I have that checks if it is the player's turn. It works for my player 1, but when it is the other player's turns it throws a nullReferenceException (I believe this is on the meanCrab.transform.position)
player.GetComponent<WeaponController>().photonView.RPC("Attack", PhotonTargets.All,
meanCrab.transform.position);
I guess what I don't understand here is why it's throwing that exception. meanCrab has a Photon View so all other players should be able to access this object with an RPC, right?
player is the player who's turn it is, BTW. I can run this without the call to meancrab.transform.position and it cycles through the multiplayer turns correctly. If I instantiate my meancrab enemy object outside of the if(Photonnetwork.playerList.Length ==1) snippet, it will create a new meancrab for each player, but I only want one for all the players.
What am I doing wrong here? Thanks!
Answer by specterdragon · Jan 20, 2014 at 01:35 AM
I may be off as I'm new to Photon, but it looks like there's a couple of issues. You're trying to call the RPC on the player not the meanCrab. It also looks like there's a syntax error (unless there's more than one way to call an RPC) because you never get the PhotonView component
If this is coming from the player, then the player needs access to a game object that represents the meanCrab, which it looks like you have.
GameObject.Find("meanCrab").GetComponent(),RPC ("Attack", PhotonTargets.All, meanCrab.transform.position);
Or something along those lines. Again, I could be way off.
If the meanCrab is going to be synced, then you'll need a PhotonView on it anyhow, so what about using OnPhotonSerializeView? Would that work for what you need?