Apologies for the unclear problem statement.
- I expect to replicate the behaviour accomplished in the lecture.
-
The player teleports back to the default location. The error is
NullReferenceException: Object reference not set to an instance of an object
TL7.SceneManagement.Portal.TeleportPlayer () (at Assets/Scripts/SceneManagement/Portal.cs:71)
TL7.SceneManagement.Portal+<Transit>d__9.MoveNext () (at Assets/Scripts/SceneManagement/Portal.cs:58)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Scripting/Coroutines.cs:17)
- 2019.1.4f1
- I followed through the code and kept all functionality near exact, except for a few changes, and then proceeded as per the video
i. I hit play.
ii. I make the player run towards a block.
The entire code for Portal.cs
:
using System.Collections;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Assertions;
using UnityEngine.SceneManagement;
namespace TL7.SceneManagement
{
public class Portal : MonoBehaviour
{
enum Destination { A, B, C, D, E };
[SerializeField, Range(-1, 100)] int sceneIndex = -1;
[SerializeField] Destination destination = Destination.A;
private Transform SpawnPoint => transform.GetChild(0);
private Portal OtherPortal
{
get
{
foreach (var portal in FindObjectsOfType<Portal>())
{
if (name == portal.name)
{
continue;
}
if (destination != portal.destination)
{
continue;
}
return portal;
}
return null;
}
}
void Start()
{
bool spawnPointInsidePortalBounds = GetComponent<BoxCollider>().bounds.Contains(SpawnPoint.position);
Assert.IsFalse(spawnPointInsidePortalBounds, $"{name}: Spawn point must be outside the portal's bounds!");
}
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
StartCoroutine(Transit());
}
}
private IEnumerator Transit()
{
if (sceneIndex >= 0)
{
DontDestroyOnLoad(gameObject);
yield return SceneManager.LoadSceneAsync(sceneIndex);
TeleportPlayer();
Destroy(gameObject);
}
else
{
Debug.LogError($"{sceneIndex} is not allowed as a scene index.");
yield break;
}
}
private void TeleportPlayer()
{
var player = GameObject.FindWithTag("Player");
print(OtherPortal.name);
player.GetComponent<NavMeshAgent>().Warp(OtherPortal.SpawnPoint.position);
player.transform.rotation = OtherPortal.SpawnPoint.rotation;
}
}
}
Upon further inspection, when the scene loads asynchronously once the collider is triggered, the number of Portals (FindObjectsByType<Portal>().Length
) becomes 3 instead of 2, and causes trouble with object references.