Object reference not set to an instance of an Object C#

Hey guys! I am pretty new to C# and am currently making my second game using this language. The game is a clone of Breakout and I have been doing really well so far but I am stuck as an error is being shown in the console. After my ball goes into the Trigger zone and tries to re-spawn on the Paddle.

My Death Field Script:

using UnityEngine;
using System.Collections;

public class DeathFieldScript : MonoBehaviour {

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}

	void OnTriggerEnter(Collider other){
		BallController ballController = other.GetComponent<BallController>();

		if(ballController){
			ballController.Die();
		}
	}
}

And also my BallController Script:

using UnityEngine;
using System.Collections;

public class BallController : MonoBehaviour {
	
	// Use this for initialization
	void Start () {
	}
	
	// Update is called once per frame
	void Update () {
		
	}

	public void Die(){
		GameObject paddleGameObject = GameObject.Find("paddle");
		Destroy(this.gameObject);
		PaddleController paddleController = paddleGameObject.GetComponent<PaddleController>();
		paddleController.SpawnBall();
	}
}

The exact error message is here:

NullReferenceException: Object reference not set to an instance of an object
BallController.Die () (at Assets/Scripts/Breakout/BallController.cs:18)
DeathFieldScript.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/Breakout/DeathFieldScript.cs:20)

Thanks to anyone who can help :slight_smile: This is my second game using C#

5 Likes

Unity is telling you that one of the things in line 18 of the BallController script doesn’t exist. In this case, that would be either the variable paddleGameObject or it’s component PaddleController. Make sure that there is such a component attached to the paddle object, and make sure that it is called “paddle”.

I don’t know if this is the problem, but you should have Destroy(this.gameObject) be the last thing this function does. You don’t want to destroy the object before you finish using it.

20 Likes

Oh man. Thank you so much :slight_smile: The problem was that I thought that when I was typing Find(“paddle”), I thought that that meant the tag not the actual GameObject. I changed it to “Player” and everything is fixed now. Thank you once again :slight_smile:

4 Likes

No problem, man. And good luck with your games.

5 Likes

Thanks. And you too :slight_smile:

Hi, I have had some problem.
I am very new to C# and was following along with Mike Geig’s tutorial on “Fun With Explosions!”
I am typing out exactly how he does it, and even pausing to make sure, but I still am getting this same error.

I am hoping someone can help.
Unity is saying the problem is on line 14
This is my script i am writing:

using UnityEngine;
using System.Collections;

public class ExplosionScript : MonoBehaviour
{

    public float force;
  

    void Update ()
    {
        if (Input.GetMouseButton (0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;
          
            if(Physics.Raycast(ray, out hit, 100))
            {
                rigidbody.AddExplosionForce(force, hit.point, 5);

            }
        }




    }
}

Georetro,

This is a common discussion here on the forum, but instead of using .Find, you could use FindGameObjectWithTag(), apparently this is much faster. It might not be if you don’t have a lot of objects, but if your scene has a lot, it might help a bit.

Cheers.

2 Likes

hi, i’m having now a similar problem but i’m not sure how to fix this, could you help me? this is my script:

using UnityEngine;
using System.Collections;

public class Patrol : MonoBehaviour {
    public Transform[] patrolPoints;
    public float moveSpeed;
    private int currentPoint;
    // Use this for initialization
    void Start () {
        transform.position = patrolPoints[0].position;
        currentPoint = 0;
    }

   
    // Update is called once per frame
    void Update () {

        if (transform.position == patrolPoints[currentPoint].position)
        {
            currentPoint++;
        }
        if (currentPoint >= patrolPoints.Length)
        {
            currentPoint = 0;
        }

        transform.position = Vector3.MoveTowards (transform.position, patrolPoints [currentPoint].position, moveSpeed * Time.deltaTime);
    }
}

this is the error: NullReferenceException: Object reference not set to an instance of an object
Patrol.Update () (at Assets/Scripts/Patrols.cs:18)

but (at least this is what i understood from the tutorial i’m following) this is not meant to be reffered to an object (i mean not line 18) except the enemy (which is referred to)… do you understand what i’m trying to say? i’m sorry, but i find it difficult to explain… anyway_ can you help me! tahtks:)

Did you add your objects in your variable patrolPoints in the inspector?
Maybe your patrolPoints array is empty. You should start looking at that first.

Let me know how it goes.

PS: Also I am not quite sure, but length return the size, so if you start your counter at 0, you will have a position that will be looking for an index that doesn’t exists. Length of 5 for example will return [0], [1], [2], [3] and [4], not [5]. Do u see what I mean?

hi, thanks for your reply. i’m sorry, but how exactly can i add an object to a variable in the inspector? and i forgot to say that before this worked, but if i add another patrol point (and add the size in the enemy inspector) it doesn’t work… in the trailer itself it used Length (

this is the trailer, you can see the code at 20:37 more or less)
1701048--106873--Schermata 2014-07-17 alle 03.15.13.png this is the enemy inspector

i’m sorry, what should i change? thank you for your time

1 Like

Well, from the video, it looks really simple.
So you have your enemy, with the script Patrol attached to it?
Do you exactly have the same setup and the same script?

You do the same way he did when adding a new patrol in the array. You drag and drop the patrol from the inspector in the Patrol Points script (the screen shot you have above).

Are all your elements (from the array in the inspector) filled wit a patrol point Transform?

Please make sure you don’t have two scripts of Patrol attached on the same enemy, that could be one of the issue if they don’t have the same size. I saw he had two scripts attached to the cube, not sure if that was on purpose.

yes, i have the script attached and the screen shot was from my inspector, so all the three sizes are filled with the patrol points. i’ve checked and i have just one script…
this is my enemy inspector right now:

and this is my script:

using UnityEngine;
using System.Collections;

public class Patrol : MonoBehaviour {
    public Transform[] patrolPoints;
    public float moveSpeed;
    private int currentPoint;
    // Use this for initialization
    void Start () {
        transform.position = patrolPoints[0].position;
        currentPoint = 0;
    }

   
    // Update is called once per frame
    void Update () {

        if (transform.position == patrolPoints[currentPoint].position)
        {
            currentPoint++;
        }
        if (currentPoint >= patrolPoints.Length)
        {
            currentPoint = 0;
        }

        transform.position = Vector3.MoveTowards (transform.position, patrolPoints [currentPoint].position, moveSpeed * Time.deltaTime);
    }
}

thank you so much once again for your help

1 Like

just so you know, i’ve solved the problem by making the game all over again. thanks anyway for your time:)

1 Like
GameObject Cube = GameObject.Find("Cube");
Cube.SetActive(false);

I have this in my FixedUpdate, and the Cube gameobject is loaded but it still says object reference not set to an instance of an object.

1 Like

I have the exact same problem,

Rigidbody2D newBullet;
newBullet = Instantiate(bullet, bs.position, bs.rotation) as Rigidbody2D;
newBullet.AddForce(bs.forward * 10000);

NullReferenceException: Object reference not set to an instance of an object
shooting.Update () (at Assets/Scripts/shooting.cs:60)

the bullet gets instantiated right in front of the character, doesn’t move, and that error comes up.

that is happen to me when i used the script of camera smooth follow y plez

I have the same error… And I can’t find any solutions…

using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;
using UnityEngine;
using System;


public class Recup_donnees_6bis : MonoBehaviour {

    class Data_struct {

        public String marker_name ;
        public Vector3 [] positions ;

    }

        private Data_struct [] nv_data ;

        GameObject [] body ;
        string[][] datas;
   
        int cpt = 0 ; // Int


    // When the script instance is being loaded

    void Awake ()

    {
        Application.targetFrameRate = 25;
    }


    // Use this for initialization

    void Start()

    {
        body = new GameObject[55];

        body [0] = GameObject.Find ("RightUpLeg");
        body [1] = GameObject.Find ("LeftUpLed");
        body [5] = GameObject.Find ("Neck");
        body [6] = GameObject.Find ("RightArm");
        body [7] = GameObject.Find ("LeftArm");
        body [8] = GameObject.Find ("Throat");
        body [9] = GameObject.Find ("Spine1");
        body [11] = GameObject.Find ("Spine");
        body [12] = GameObject.Find ("Hips");
        body [13] = GameObject.Find ("Scalp");
        body [14] = GameObject.Find ("HeadTop_End");
        body [15] = GameObject.Find ("R_Temple");
        body [16] = GameObject.Find ("L_Temple");
        body [17] = GameObject.Find ("RightForeArm");
        body [21] = GameObject.Find ("RightHand");
        body [23] = GameObject.Find ("RightHandIndex1");
        body [24] = GameObject.Find ("RightHandThumb2");
        body [25] = GameObject.Find ("RightHandPinky2");
        body [26] = GameObject.Find ("LeftForeArm");
        body [30] = GameObject.Find ("LeftHand");
        body [32] = GameObject.Find ("LeftHandIndex1");
        body [33] = GameObject.Find ("LeftHandThumb2");
        body [34] = GameObject.Find ("LeftHandPinky2");
        body [35] = GameObject.Find ("RightLed");
        body [38] = GameObject.Find ("RightFoot");
        body [41] = GameObject.Find ("RightFootToeBase_End");
        body [42] = GameObject.Find ("RightToeBase");
        body [45] = GameObject.Find ("LeftLed");
        body [48] = GameObject.Find ("LeftFoot");
        body [51] = GameObject.Find ("LeftFootToeBase_End");
        body [53] = GameObject.Find ("LeftToeBase");

        StreamReader reader = new StreamReader ("Suj01_PI_DP_C00_1.txt");
       
        using (reader) {
           
            string line = " ";
            int lineNumber = 10;

                for (int i = 0; i < lineNumber; i++)
                {
                    line = reader.ReadLine();
                    if (line == null) return;
                }
           
            string line_10;
            line_10 = line;
            string[] names = line_10.Split (new String[] {",",",,,"},StringSplitOptions.RemoveEmptyEntries);

            nv_data = new Data_struct[names.Length] ;

                for (int i =0 ; i< names.Length; ++i )
                {
                    nv_data[i] = new Data_struct () ;
                    nv_data[i].marker_name = names[i] ;
                }

           
            line = reader.ReadLine();
            string line_11;
            line_11 = line;
            string[] axes = line_11.Split(new String[] {"Field #",","},StringSplitOptions.RemoveEmptyEntries);

            datas = new string[4000][];

            int counter = 0;
            while (line != null) {
                counter++;
                line = reader.ReadLine();

                if (line == "ANALOG")
                break ;

                if ((counter %3) != 1)                    continue;

                string lines_datas;
                lines_datas = line;
                datas[cpt] = lines_datas.Split(new string[] {","},StringSplitOptions.RemoveEmptyEntries);

                line = reader.ReadLine();

                cpt ++ ;   
               
            }

                for (int i = 0 ; i < cpt ; ++i ) // We parse every line of datas
                {
                    for (int j = 1 ; j < names.Length+1 ; j++ )
                {
                    nv_data[j-1].positions = new Vector3[cpt];
               
                nv_data[j-1].positions[i].x = float.Parse(datas[i][j*3-2]);
                nv_data[j-1].positions[i].y = float.Parse(datas[i][j*3-1]);
                nv_data[j-1].positions[i].z = float.Parse(datas[i][j*3]);

                }
               
            }

        }
       
     }

    // Update is called once per frame
    void Update () {

        // To associate names_markers to avatar_joints :

        for (int i = 0; i < cpt; ++i) {

                        for (int k = 0; k < body.Length; ++k)

                                body [k].transform.position = nv_data[k].positions[i];
                                Debug.Log(body[1].transform.position);

                }

    }

}

My problem is about the line :
body [k].transform.position = nv_data[k].positions*;*
I think it’s because the string “nv_data” has been initialized and used in “void start ()” and here I’m in “void update”. How can I used this string in void update () ?
I need this code to make an animation : combining datas (get from the text file) to an avatar.
Datas in text file corresponds to names of markers (on real human body) and the avatar has some joints. So I associated some markers (names) to joints. And now I want that the datas concerning positions of markers (names) would be associated to the joints that I have chosen.
Could you help me, please ?
I’m not english, so my apologies for my writing.
Thank you

Im trying to expand on the Unity Space Shooter Tutorial and im getting the error
“NullReferenceException: Object reference not set to an instance of an object”

Im quite new to unity.

Any help would be greatly appreciated.

using UnityEngine;
using System.Collections;

public class Done_DestroyByContact : MonoBehaviour
{
public GameObject explosion;
public GameObject playerExplosion;
public int scoreValue;
private Done_GameController gameController;
private Respawn respawn;

void Start ()
{
GameObject gameControllerObject = GameObject.FindGameObjectWithTag (“GameController”);
if (gameControllerObject != null)
{
gameController = gameControllerObject.GetComponent <Done_GameController>();
}
if (gameController == null)
{
Debug.Log (“Cannot find ‘GameController’ script”);
}
}

void OnTriggerEnter (Collider other)
{
if (other.tag == “Boundary” || other.tag == “Enemy”)
{
return;
}

if (explosion != null)
{
Instantiate(explosion, transform.position, transform.rotation);
}

if (other.tag == “Player”)
{
gameController.UpdateLives();
Instantiate(playerExplosion, other.transform.position, other.transform.rotation);

}

gameController.AddScore(scoreValue);
Destroy (other.gameObject);
Destroy (this.gameObject);
respawn.CheckLives ();
Debug.Log(“AFTER CHECK LIVES”);

}
}

Getting this error when I left click and it says it is in the lines 28 and 15 so I have no idea what to do. Any help will do.

using UnityEngine;
using System.Collections;

public class PlayerShooting : MonoBehaviour {

public float firerate = 0.5f;
float cooldown = 0;
public float damage = 25f;

// Update is called once per frame
void Update () {

cooldown -= Time.deltaTime;
if (Input.GetButton (“Fire1”)) {
fire ();

}

}
void fire(){
if (cooldown > 0) {
return;

}

Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);
Transform hitTransform;
Vector3 hitPoint;

hitTransform = FindClosestHitObject (ray, out hitPoint);

if (hitTransform != null) {
Debug.Log (“Fired Gun”);

Health h = hitTransform.GetComponent();

while(h == null && hitTransform.parent){
hitTransform = hitTransform.parent;
h = hitTransform.GetComponent();
}

if(h !=null){
h.TakeDamage(damage);
}

}

cooldown = firerate;
}

Transform FindClosestHitObject(Ray ray, out Vector3 hitPoint){

RaycastHit[ ] hits = Physics.RaycastAll (ray);

Transform closestHit = null;
float distance = 0;
hitPoint = Vector3.zero;

foreach (RaycastHit hit in hits) {
if(hit.transform != this.transform && (closestHit==null || hit.distance < distance )){

closestHit = hit.transform;
distance = hit.distance;
hitPoint = hit.point;
}
}
return closestHit;
}
}

Hey I am getting the same problem I am using 2 scripts one script uses a function from another script

This script is called Attack

using UnityEngine;
using System.Collections;
public class Attack : MonoBehaviour {
Animator animator;
Weapon weapon;
void Update () {
animator = GetComponent ();
if (Input.GetKey (KeyCode.Space)) {
animator.SetBool (“Attack”, true);
weapon.WeaponAtk(true, 1);
}
else
{
animator.SetBool (“Attack”, false);
}
}
}

And this is the script called Weapon with the function inside of it called WeaponAtk

using UnityEngine;
using System.Collections;
public class Weapon : MonoBehaviour{
public bool Attacking;
public int Dmg;
public void WeaponAtk (bool attacking, int dmg)
{
attacking = Attacking;
dmg = Dmg;
if(attacking == true)
{
print ("Damage Given " + dmg);
}
}
}