I’m making a racing game with checkpoints.
I’m instantiating a player in a script called manager and also setting the tag name of the instantiated player object to “Player”. But also the prefabbed object is already tagged Player
Manager Script :
Instantiate(player1Car, p1Pos.position, p1Pos.rotation);
I can now move my instantiated player around the track.
But I’m getting a null reference error in my checkpoint script when my character crosses a checkpoint in my game.
But my code in the checkpoint script is FindWithTag(“Player”) and I set the tag of the instantiated player object to “Player” when I created it.
So why can’t it find player? why can’t it find the tag?
CheckPoint Script :
void Start()
{
//find the instantiated player and reference it with PlayerTransform
PlayerTransform = GameObject.FindWithTag("Player").transform;
}
//when the player car goes through the checkpoint this trigger is called
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
// the next line of code is where the error appears.
int cCheckPoint = PlayerTransform.GetComponent<PlayerCheckPoints>().currentCheckPoint;
int cLap = PlayerTransform.GetComponent<PlayerCheckPoints>().currentLap;
the error that appears on that line (int cCheckPoint etc) is
NullReferenceException: Object reference not set to an instance of an object
CheckPoint.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/Checkpoints/CheckPoint.cs:56)
Help really appreciated. This has been bugging me all day. I hope I explained it right and it’s not too confusing.