I am getting a null reference error which i am not able to figure out why this error is coming and also despite the null reference error it is performing the functionality which it should perform. Following is the code where it is generating error, here is my **LevelManager** Class code which spawn the player
PlayerSpawn playerSpawner = new PlayerSpawn();
playerSpawner.OnPlayerSpawned += CurrentPlayerSpawned;
playerSpawner.entity = playerObject;
playerSpawner.Spawn(leveDataList[_currentLevelNumber].playerSpawnPosition);
// check if playerSpawner is null before calling the Spawn method
/* if (playerSpawner != null)
{
playerSpawner.entity = playerObject;
playerSpawner.Spawn(leveDataList[_currentLevelNumber].playerSpawnPosition);
}
else
{
Debug.LogError("PlayerSpawner is null!");
}*/
It always run else condition and my player not spawned but if i not write my spawn code in this if else then it spawn the player at the exact location which it should have but still gives me a null reference error in spawn line
Here is My **PlayerSpawn ** code
public class PlayerSpawn : EntitySpawner
{
public event Action OnPlayerSpawned;
public override GameObject Spawn(Transform positionTransform)
{
GameObject go = base.Spawn(positionTransform);
OnPlayerSpawned?.Invoke(go);
return go;
}
}
and my **EntitySpawner** code is here
public class EntitySpawner : MonoBehaviour
{
public GameObject entity;
public Transform defaultPosition;
public virtual GameObject Spawn()
{
return Spawn(defaultPosition);
}
public virtual GameObject Spawn(Transform positionTransform)
{
return GameObject.Instantiate(entity, positionTransform.position, positionTransform.rotation);
}
}
Another problem i am facing is that my player spawn code runs when in OnEnable of my LevelManager class and when i play game while remaining inside the same scene and my if else condition removes then despite giving the null reference error it spawn the player but when i come from the intro scene then it did not spawn the player
I tried a lot but i am not able to figure out why this is giving null refernce error, here is the error which i am getting
![alt text][1]
[1]: /storage/temp/206951-null-reference-error.png
↧