Hello Guys,
i work on my platformer and i followed a tutorial for an endless runner with generating platforms when the player is nearby specific endpoints which are set for the platform prefabs.
In that script there are two functions for spawning levels, first to spawn at start of the level and this can set to 1 or 10 or 100 without problems.
The problem is that if the character reaches the end of the last preloaded Platform, no new one gets loaded.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelGenerator : MonoBehaviour
{
private const float PLAYER_DISTANCE_SPAWN_LEVEL_PART = 200f;
[SerializeField] private Transform LevelPart_Start;
[SerializeField] private List<Transform> LevelList;
[SerializeField] private GameObject Player;
private Vector3 lastEndPosition;
private void Awake() {
lastEndPosition = LevelPart_Start.Find("EndPosition").position;
int startingSpawnLevelParts = 2;
for (int i = 0; i < startingSpawnLevelParts; i++)
{
SpawnLevelPart();
}
}
private void Update() {
if (Vector3.Distance(Player.transform.position, lastEndPosition) < PLAYER_DISTANCE_SPAWN_LEVEL_PART)
{
SpawnLevelPart();
}
}
private void SpawnLevelPart() {
Transform chosenLevelPart = LevelList[Random.Range(0, LevelList.Count)];
Transform lastLevelPartTransform = SpawnLevelPart(chosenLevelPart, lastEndPosition);
lastEndPosition = lastLevelPartTransform.Find("Endposition").position;
}
private Transform SpawnLevelPart(Transform levelPart, Vector3 spawnPosition)
{
Transform levelPartTransform = Instantiate(levelPart, spawnPosition, Quaternion.identity);
return levelPartTransform;
}
}
I also get an warning message about Null, but i have set all items into the inspector. (Player GameObject, Starting Level and the List is filled with the platforms)
NullReferenceException: Object reference not set to an instance of an object
LevelGenerator.SpawnLevelPart () (at Assets/Scripts/LevelGenerator.cs:38)
LevelGenerator.Awake () (at Assets/Scripts/LevelGenerator.cs:23)
As iam really new to coding and struggle already a few days with that issue, i thought maybe asking for advice in the community.
Hope we can find a solution for it and thanks already for your help.