NullReferenceException: Object Reference not set to an instance of an object
I am making a 2D game in the style of pac-man. I am using a script to place "dots" in the scene (called pacdot in my script). This script is attached to a gameobect called placer which moves round the scene, placing the dots. However as my game contains a maze and therefor I have a ray-casting function that returns a boolean value based on weather the placer game object is in contact with the collider from the maze. If false is returned by the function then no dots are placed and instead the placer moves to the next location. My game contains waypoints. These waypoints are also detected by the raycasting function, however I want dots to be placed over these invisible waypoints. To do this i have given all my waypoints the tag of "Waypoint". I then detect in the ray cast function weather i have detected a waypoint, and if so the function still returns true. I am receiving the error as shown in the title however for line 16 and i do not understand what i am doing wrong. Any help would be really appreciated. :)
using UnityEngine; using System.Collections;
public class Place : MonoBehaviour {
public GameObject pacdot;
// Use this for initialization
void Start () {
}
bool valid(Vector2 dir) {
Vector2 pos = transform.position;
RaycastHit2D hit = Physics2D.Linecast (pos, pos);
if (hit.collider.gameObject.tag != "Waypoint")
return (hit.collider == GetComponent<Collider2D> ());
else return(true);
}
// Update is called once per frame
void FixedUpdate () {
if (valid(Vector2.right)) {
if (transform.position.y > 1) {
if (transform.position.x < 28)
Instantiate (pacdot, new Vector2 (transform.position.x, transform.position.y), Quaternion.identity);
transform.Translate (1, 0, 0);
if (transform.position.x > 28)
transform.Translate (-28, -1, 0);
}
}
if (valid (Vector2.right) == false) {
transform.Translate (1, 0, 0);
}
}
}
I'm sorry but it's hard to tell which is line 16, as your question is posted... Could you copy-paste the line that's causing the problem?
Looking at your code, the only line that looks like it can cause a problem is:
return (hit.collider == GetComponent ());
From what I understand, you are telling that function to return true if the raycast collides with the placer! - GetComponent ()
refers to the Collider2D attached to the placer, if there is one. So either you made a mistake and did not want the function to return true if the raycast collides with the placer, or you forgot to attach a Collider2D to the placer!
Or I am just completely wrong about this.
Your answer
Follow this Question
Related Questions
Raycast not changing value 0 Answers
Bounds and extents of a tilemap collider across differing y axes, Tilemap collider bounds 0 Answers
Not all paths return a value 1 Answer
Strange Raycast problem 0 Answers