Thanks!
I like the idea of using the portal.cs to assign a respawn point, but I’m not sure on how to execute it. I’ve had a go with the changes below, but no dice. I get an NRE ‘object not set’ error on this line:
respawner.respawnLocation = spawnPoint.transform;
Basically, I know that I want to get the portal I came in from, and pass the player’s Portal.cs spawnPoint to the Respawner.cs to update the respawnLocation. I feel like it’s close, but not there yet. Any tips? Thanks!
Full Script Below:
using System.Collections;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.SceneManagement;
using RPG.Control;
using RPG.Attributes;
namespace RPG.SceneManagement
{
public class Portal : MonoBehaviour
{
enum DestinationIdenifier
{
A, B
}
[SerializeField] int sceneToLoad = -1;
[SerializeField] Transform spawnPoint;
[SerializeField] DestinationIdenifier destination;
[SerializeField] float fadeOutTime = 1f;
[SerializeField] float fadeInTime = 2f;
[SerializeField] float fadeWaitTime = 0.5f;
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
StartCoroutine(Transition());
}
}
private IEnumerator Transition()
{
if (sceneToLoad < 0)
{
Debug.LogError("Scene to load is not set.");
yield break;
}
DontDestroyOnLoad(gameObject);
Fader fader = FindObjectOfType<Fader>();
SavingWrapper wrapper = FindObjectOfType<SavingWrapper>();
PlayerController playerController = GameObject.FindWithTag("Player").GetComponent<PlayerController>();
playerController.enabled = false;
yield return fader.FadeOut(fadeOutTime);
wrapper.Save();
yield return SceneManager.LoadSceneAsync(sceneToLoad);
PlayerController newPlayerController = GameObject.FindWithTag("Player").GetComponent<PlayerController>();
newPlayerController.enabled = false;
wrapper.Load();
Portal otherPortal = GetOtherPortal();
UpdatePlayer(otherPortal);
wrapper.Save();
yield return new WaitForSeconds(fadeWaitTime);
fader.FadeIn(fadeInTime);
newPlayerController.enabled = true;
Destroy(gameObject);
}
private Portal GetOtherPortal()
{
foreach (Portal portal in FindObjectsOfType<Portal>())
{
if (portal == this) { continue; }
if (portal.destination != destination) { continue; }
return portal;
}
return null;
}
private void UpdatePlayer(Portal otherPortal)
{
GameObject player = GameObject.FindWithTag("Player");
player.GetComponent<NavMeshAgent>().Warp(otherPortal.spawnPoint.position);
player.transform.rotation = otherPortal.spawnPoint.rotation;
}
void Update()
{
if (GameObject.FindWithTag("Player").GetComponent<Health>().IsDead())
{
Respawner respawner = this.GetComponent<Respawner>();
spawnPoint = GetOtherPortal().spawnPoint.transform;
respawner.respawnLocation = spawnPoint.transform;
respawner.Respawn();
}
}
}
}