How to instantiate the Player Prefab as an Object with PUN2,Accessing the Player as an Object with PUN2
Hey guys, I'm trying to instantiate my player as an object and not a clone whe n calling PhotonnNetwork.Instatiate withing OnJoinedRoom(). I have a view scripts that used to grab the player object before I implemented this multiplayer feature, and I would like to find a way to adapt it so that I can still use the same scripts.
this is how i instantiated the player:
public GameObject playerPrefab;
GameObject player = PhotonNetwork.Instantiate(this.playerPrefab.name, transform.position, Quaternion.identity, 0);
and this is an example of one of the scripts that accesses the player object, this one is located within my whipAttackScript"
void Start()
{
anim = whip.GetComponent<Animator>();
playerAnim = GameObject.Find("Player").GetComponent<Animator>();
audioSource = GetComponent<AudioSource>();
}
void Update()
{
if (timeBtwnAttack <= 0)
{
if (Input.GetKey(KeyCode.Z))
{
anim.SetTrigger("usingWhip");
playerAnim.SetTrigger("isAttacking");
audioSource.PlayOneShot(attackSound, 1F);
Collider2D[] enemiesToDamage = Physics2D.OverlapBoxAll(attackPos.position, new Vector2(attackRangeX,attackRangeY),0, whatIsEnemies);
for (int i = 0; i < enemiesToDamage.Length; i++)
{
enemiesToDamage[i].GetComponent<Enemy>().TakeDamage(damage);
}
timeBtwnAttack = startTimeBtwAttack;
}
}
thanks for the help!
Answer by Captain_Pineapple · Nov 13, 2019 at 07:51 PM
Hey there,
from my experience the stuff you did will not work like you want it with photon. Since you can never be sure how long a message will need you always have to work eventdriven when using networking. So in this way all scripts who have to access the player either have to wait until the player is instantiated to do further stuff or you could move the instantiation to an "onEnable" function and enable all needed scripts in your player start function. (the latter might be tricky if your scripts get en-/disabled somewhere along the gameplay since they will then replay the initialisation)
the probably best version would be to have your playerobjects find all needed other transforms and add the needed components there.
as you can see there are quite some different ways of how to go about this. There is no "true right way" for this. Only a way that works well for your game setup. But in the end you always have to catch the worst case which can only be done if everything basically is a set chain of events that will not break if some steps takes longer than usual.
Your answer
Follow this Question
Related Questions
Check what group id you have after being instantiated. (PUN) 1 Answer
C# Photon Networking - Preventing duplicate GameObjects from spawning on Join. 1 Answer
i can't see other player with photon cloud server,I Can't see each other player in photon cloud 2 Answers
Keeping an object in a multiplayer scene, when a player joins. 3 Answers
I get an error message every time i run this script? Any ideas? 0 Answers