K
K
Kirill Kichigin2017-03-28 13:59:03
Unity
Kirill Kichigin, 2017-03-28 13:59:03

Error object reference not set to an instance of an object. Where is wrong?

Here is a map. It has a cube tagged Job and another one tagged Box.
When a player rolls a box tagged cube into a Job tagged cube,
5 should be added to the money.
BUT, the place of this gives an error object reference not set to an instance of an object.
Please find the errors:
script on the job object:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Job : MonoBehaviour {
  public float addmoney;
  // Use this for initialization
  void Start () {
    
  }
  
  // Update is called once per frame
  void Update () {
    
  }
  void OnTriggerEnter(Collider col)                
    {                                            
        if(col.CompareTag("Box"))             
        {                                     
        	PlayerMoney pt = col.GetComponent<PlayerMoney>();
        	addmoney += pt.money;
        }                                        
    }                                   
}

Script on FPScontroller object:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

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

Where is the mistake?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniil Basmanov, 2017-03-28
@KiR_Ka

If you throw out all the garbage from your scripts, then the following remains:

using UnityEngine;

public class Job : MonoBehaviour
{
    public float addmoney;

    private void OnTriggerEnter(Collider col)
    {
        if (col.CompareTag("Box"))
        {
            PlayerMoney pt = col.GetComponent<PlayerMoney>();
            addmoney += pt.money;
        }
    }
}

using UnityEngine;

public class PlayerMoney : MonoBehaviour
{
    public int money;
}

A nullref can only be in one line:
This means that there was no PlayerMoney script on the collider with the Box tag. Either you did not hang it, or it hangs higher in the hierarchy. Another option is that some other object has a tag besides a cube with money.
If for some reason the collider needs to be below the script in the hierarchy, you can use GetComponentInParent to find it .
Related Links:
MSDN - NullReferenceException
What is a Null Reference Exception?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question