As stated in the title, I get this error when I try to instantiate a gameobject from a prefab, using PUN:
InvalidCastException: Cannot cast from source type to destination type.
NetworkingPeer.DoInstantiate (ExitGames.Client.Photon.Hashtable evData, .PhotonPlayer photonPlayer, UnityEngine.GameObject resourceGameObject) (at Assets/Photon/Photon Unity Networking/Plugins/PhotonNetwork/NetworkingPeer.cs:3069)
PhotonNetwork.Instantiate (System.String prefabName, Vector3 position, Quaternion rotation, Int32 group, System.Object[] data) (at Assets/Photon/Photon Unity Networking/Plugins/PhotonNetwork/PhotonNetwork.cs:2493)
PhotonNetwork.Instantiate (System.String prefabName, Vector3 position, Quaternion rotation, Int32 group) (at Assets/Photon/Photon Unity Networking/Plugins/PhotonNetwork/PhotonNetwork.cs:2437)
GunController.EquipGun (.Gun gunToEquip) (at Assets/Scripts/Gun/GunController.cs:38)
GunController.init () (at Assets/Scripts/Gun/GunController.cs:19)
NetworkPlayer.Start () (at Assets/Scripts/Network/NetworkPlayer.cs:20)
Old, working code:
equippedGun = Instantiate(gunToEquip, weaponHold.position, weaponHold.rotation) as Gun;
equippedGun.transform.parent = weaponHold;
New code, using Photon:
equippedGun = PhotonNetwork.Instantiate(gunToEquip.name, weaponHold.position, weaponHold.rotation, 1).GetComponent<Gun>();
equippedGun.transform.parent = weaponHold;
Where:
- equippedGun is by default an empty variable of type Gun
- gunToEquip is a GameObject variable (with the component Gun) that gets passed into the function. (PhotonNetwork.Instantiate takes in the name of the prefab, not the actual prefab, thus gunToEquip.name)
In this particular case, gunToEquip is the default gun that fails to instantiate, which is set by the unity inspector
- weaponHold is just a transform variable, again set by the inspector.
(I do GetComponent instead of “as Gun”, as normal instantiate returns Object and PhotonNetwork.Instantiate returns GameObject)
I somehow managed to fix it for my player prefab, I have no idea how. I was just changing and reverting stuff until it magically worked. Any solutions?
EDIT: not sure if it is the problem, but here are the prefab settings: Imgur: The magic of the Internet