Sunday, February 8, 2015

Destroying Enemy using Photon Network RPC call

So I hit this problem with the synchronization problem with Photon Network where example

Player 1 Host the game
Player 2 Join the game

both player fighting the same enemy1

Player 2 kill the enemy but player 1 still see the enemy

This is because if you are using the

PhotonNetwork.Destroy(gameObject);

Player 2 cannot call this function because he is not the owner of this object, only Player 1 can call this function, to fix this, we must use the RPC call as below


/////////////////inside enemy.cs//////////////////////////////////////////////////

[RPC]
    public void gethit(float getdamage)
    {
        if(PhotonNetwork.isMasterClient)
        {
            life-=getdamage;
            
            if(life<=0.0f)
            {
                
                PhotonNetwork.Destroy(gameObject);
            }
        }
    }

///////////////////////////////////////////////////////////////////////////////

first, inside your enemy script, you put the tag [RPC] on top of your function

then, make sure only master client do the deducting life because you dont want everyone deducting life, example if 5 player all do the deducting life the enemy get 1 bullet but deduct life 5 times

then finally, only "MASTER CLIENT" can call the PhotonNetwork.Destroy because he own the object

//////////////////////////inside bullet.cs ////////////////////////

void OnCollisionEnter(Collision collision
    {
        
        if(collision.collider.gameObject.GetComponent<enemy>())
        {
            //collision.collider.gameObject.GetComponent<enemy>().gethit(damage);

            collision.collider.gameObject.GetComponent<PhotonView>().RPC ("gethit",PhotonTargets.
MasterClient,damage);


    }


/////////////////////////////////////

Then, inside your bullet script, where originally, you will use the

collision.collider.gameObject.GetComponent<enemy>().gethit(damage);

Now, you use

collision.collider.gameObject.GetComponent<PhotonView>().RPC ("gethit",PhotonTargets.MasterClient,damage);


So the original one is to ask the enemy script to execute the "gethit" function for "SELF"
-> example player 2 kill the enemy, player 2 calling the "gethit" function but not player1

the new one is to ask the photon view RPC call to ask "MASTER CLIENT" to execute that gethit function
-> so if the room have 3 player, only "MASTER CLIENT" will call the "gethit" function


1 comment:

  1. void OnCollisionEnter(Collision collision)
    {

    if(collision.collider.gameObject.GetComponent())
    {
    //collision.collider.gameObject.GetComponent().gethit(damage);

    collision.collider.gameObject.GetComponent().RPC ("gethit",PhotonTargets.MasterClient,damage);

    Where did you get "damage"?

    ReplyDelete