When exiting scenes I would get the following errors for each instantiated object in the level:
OnDestroy for PhotonView View (0)1001 on CharacterPlaceholder(Clone) but GO is still in instantiatedObjects. instantiationId: 1001. Use PhotonNetwork.Destroy().
Failed to 'network-remove' GameObject because it's null.
I searched the Internet and Exit Games forums but found little help that actually solved the problem. I found plenty of other people reporting the same issue.
I tried reading the PUN documentation but that was unhelpful as were any of the samples that I tried so I experimented.
I now have a work round which avoids the warnings and errors.
/// Tidies up before exit from the scene.
/// Attempts to destroy network objects correctly.
/// Pauses the messages while the scene changes.
private static void TidyUpBeforeExit()
{
// Destroy any photonView game objects.
PhotonView[] views =
GameObject.FindObjectsOfType<photonview>();
// Whichever client exits first cannot
// destroy the objects owned by
// another client.
foreach (PhotonView view in views)
{
GameObject obj = view.gameObject;
if (view.isMine)
{
// Clients can destroy their
// own instantiated objects
PhotonNetwork.Destroy (obj);
}
else
{
// Clients cannot destroy objects
// instantiated by other clients.
// This avoids the error by
// removing the instantiated
// object before the network view
// is destroyed
if (PhotonNetwork.
networkingPeer.
instantiatedObjects.
ContainsKey(view.instantiationId))
{
PhotonNetwork.
networkingPeer.
instantiatedObjects.
Remove (view.instantiationId);
}
}
}
// By pausing and starting the
// messages manually I can start
// any client or server in any
// order and all spawn messages
// are retained.
PhotonNetwork.SetSendingEnabled(0, false);
PhotonNetwork.isMessageQueueRunning = false;
}
I simply include that method before any scene change.