Here's my portal code:
Code: Select all
using System;
using System.Collections;
using RPG.Saving;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.SceneManagement;
using RPG.Control;
namespace RPG.SceneManagement
{
public class Portal : MonoBehaviour
{
enum DestinationIdentifier
{
A, B, C, D, E // these are used to match up with the right portal (may have more than one portal per scene)
}
[SerializeField] int sceneToLoad = -1;
[SerializeField] Transform spawnPoint;
[SerializeField] DestinationIdentifier destination;
[SerializeField] float fadeOutTime = 1f;
[SerializeField] float fadeInTime = 2f;
[SerializeField] float fadeWaitTime = 0.5f;
[SerializeField] Character character = null;
GameObject player;
private void OnTriggerEnter(Collider other) {
if (other.tag == "Player")
{
StartCoroutine(Transition());
}
}
private IEnumerator Transition()
{
if (sceneToLoad < 0)
{
Debug.LogError("Scene to load not set.");
yield break;
}
DontDestroyOnLoad(gameObject);
Fader fader = FindObjectOfType<Fader>();
SavingWrapper savingWrapper = FindObjectOfType<SavingWrapper>();
player = GameObject.FindWithTag("Player");
player.GetComponent<PlayerController>().enabled = false; //disable player control
yield return fader.FadeOut(fadeOutTime);
character.OnSaveInventory();
savingWrapper.Save();
yield return SceneManager.LoadSceneAsync(sceneToLoad);
player = GameObject.FindWithTag("Player"); // this is a new scene with a new player, so you need to find the player again.
player.GetComponent<PlayerController>().enabled = false;
savingWrapper.Load();
Portal otherPortal = GetOtherPortal();
UpdatePlayer(otherPortal);
savingWrapper.Save();
yield return new WaitForSeconds(fadeWaitTime);
fader.FadeIn(fadeInTime);
player.GetComponent<PlayerController>().enabled = true;
Destroy(gameObject);
}
private void UpdatePlayer(Portal otherPortal)
{
GameObject player = GameObject.FindWithTag("Player");
player.GetComponent<NavMeshAgent>().enabled = false; // disable the navMeshAgent while we are placing the player
player.transform.position = otherPortal.spawnPoint.position;
player.transform.rotation = otherPortal.spawnPoint.rotation;
player.GetComponent<NavMeshAgent>().enabled = true; // renable navMeshAgent after placing player
}
private Portal GetOtherPortal()
{
foreach (Portal portal in FindObjectsOfType<Portal>())
{
if (portal == this) continue;
if (portal.destination != destination) continue;
return portal;
}
return null;
}
}
}