C# NullReferenceException

Hi,

I keep getting this error when I start my game:

NullReferenceException: Object reference not set to an instance of an object
PlayerAttack.Start () (at Assets/Standard Assets/Scripts/PlayerAttack.cs:19)

And I don’t know what to do with it. Basically I’m trying to copy the content from a List KnownNames in script PlayerKnowledge, into a new List<> Knowledge in script PlayerAttack. Then I can further down in PlayerAttack compare a specific string with the content in Knowledge<>, and if the string exists there, then do a specific attack.

Any help would be greatly appreciated :slight_smile:


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

public class PlayerAttack : MonoBehaviour {
	public GameObject target;
	private PlayerKnowledge playerKnowledge;
	private List<string> knowledge = new List<string>();
	
	// Use this for initialization
	void Start () {
		
	//This is the line the error points to
		var know = playerKnowledge.knownNames;
	
        //Anyone know how to print content of List<> BTW?
		Debug.Log("know returns" + know);
		
		if(know != null){
		knowledge.AddRange(know);
		Debug.Log("knowledge !null returns: " + knowledge);
		}
		
	}

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

public class PlayerKnowledge : MonoBehaviour {
	public List<string> knownNames; 
	public GameObject item;
	private GameObject book; 
	
	// Use this for initialization
	void Start () {
		var knownNames = new List<string>();
		knownNames.Add("Test");
		
		Debug.Log("PlayerKnowledge Start: " + knownNames);
		
	}

I don’t see where playerKnowledge is being initialised in your code. If you don’t initialise it then as soon as you try to dereference it to obtain ‘knownNames’ you will see the exception you describe.

Given the names of your classes, I suspect that they are both found as components on your player object. If that’s the case, then use a line like this in PlayerAttack.Start:

playerKnowledge = GetComponent<PlayerKnowledge>();
if (null == playerKnowledge){
 Debug.LogError("PlayerKnowledge not found. This code will crash");
}

If you know that an object with a PlayerAttack component must always have a PlayerKnowledge component too, then you might consider using a [RequireComponent(typeof(PlayerKnowledge))] tag to describe your attack component, otherwise add a null test before var know = …