- Home /
Error says object reference not set when it really is?
Hey guys I feel like Ive tried everything here and I cant get this error to go away. Im making a 2D platformer and would like to add some spikes to the game. If the player collides with them, they "die" and respawn at the beginning of the map. I placed the spike sprite in the game and attached my "Hazard" script to it (no debugging errors what so ever). The spike "Is Triggered" when the player (who has the tag "Player") walks into it. I created an empty game object called "start" and placed it at the beginning of the map. This is where the player will transfer to when they collide with the spike. I drag the "start" object and attach it to the Hazard Script so that they are linked together.
When I press play, the player moves fine and as soon as it touches the spike, it flashes the error "NullReferenceException: Object reference not set to an instance of an object". I reference the start object though so I dont understand what it means by it not being set?! Is there something else that it is having difficulty with?
Here is the Hazards Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hazard : MonoBehaviour {
private Controls player;
public Transform start;
void Start()
{
player = FindObjectOfType<Controls>();
}
void Update()
{
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
player.transform.position = start.position;
}
}
}
Seriously, any help would be amazing. I feel like ive tried so many things and I cant get it to work. Thanks guys!
Here's a question: is your 'player' object being found properly in Start?
What if you don't store that and you get the component from the 'other' object in OnTriggerEnter2D. If it has the tag "Player" it likely has the component too, right?
Thank you so much for your help! Seriously really appreciate it!
As @Habitablaba said, most likely player
isn't set properly. Why not make that a public property and set it in the inspector like you do with start
?
Thank you so much for your input, definitely pointed me in the right direction!
Answer by Laiken · Jun 21, 2017 at 06:24 PM
Drag you "Controls" script to any game object in the scene in case you didn't. (if you didn't do it, the script is in your asset folder but not in the scene, that's why FindObjectOfType won't find it )
Thank you so much! Seriously! Now that I see it, it makes total sense. Ive been jumping between a couple tutorials and I must not have had the script attached properly!
Your answer
Follow this Question
Related Questions
Getting an object to re-spawn/ transform player back to the beginning 1 Answer
Update instantiates more than 1 object 2 Answers
transform.position not setting position OR animation setting position even though it shouldn't 0 Answers
[2D] Get the position of an object outside the scope 2 Answers
moving objects with transform position 2 Answers