- Home /
NullReferenceException from a script after linking prefab with drag and drop in inspector. WTF?
Hi guys, sorry to bother you all, I'm quite a noob in Unity but I'm learning. I have this problem: I'm creating a class that for the moment just Instantiates a prefab.
using UnityEngine;
using System.Collections;
public class DeckController : MonoBehaviour {
public GameObject testCard;
public GameObject DrawCard()
{
Debug.Log("testCard: " + testCard.name);
GameObject temp = (GameObject) Instantiate(testCard);
Debug.Log("tempIsNow: " + temp.name);
return temp;
}
}
I dragged the prefab form the Prefabs folder into the public variable: testCard. As you can see here:
What happens is that I get a runtime exception:
NullReferenceException: Object reference not set to an instance of an object DeckController.DrawCard () (at Assets/Scripts/CardController/DeckController.cs:10)
Row 10 is where there is the first Debug.Log, so it seems that testCard is set to null. I don't understand how this is possible since even in official tutorials this seemed to be the procedure... :( Help please!
Answer by Bunny83 · Oct 11, 2013 at 04:42 PM
Just a guess but:
Add this line at the very beginning of your DrawCard function:
Debug.Log("GameObject name: " + gameObject.name);
to reveal that this script is attached to another object ;)
Thanks so much! I solve the problem. In the moment that you supposed that the script was not in the correct position. I understood that the problem was something similar. DrawCard() was called from another script where there was a reference to the Class DeckController ins$$anonymous$$d of a reference to the component DeckController of the game object Deck1. Thanks a lot, you set me on the right road!
I wish there was more info here - I am having the same problem, but I don't fully understand what the solution was.
He has attached the script to more than one object. He did initialize the variable properly on the object he actually cared about. However he had another instance somewhere else where he did not assign the prefab in the inspector. So he did not call his DrawCard method on the instance he originally expected but on that "other" instance. Note that prefabs stored in the project are also "instances" but not in the scene. They exist in memory but don't do anything on their own.
If you have more questions (and also for the future), please do not post questions in comments to other questions / answers. If you have an issue, ask your own question and add your specific details to the description. (we do not own crystal balls to read your $$anonymous$$d. ;) )
Your answer
Follow this Question
Related Questions
very weird NullReferenceException error causeing one script to break another 2 Answers
Put a prefab in Hierarchy without using Instantiate ? (from code) 2 Answers
Prefab GameObject's can not be made active! 3 Answers
Referencing gameObject from script after Instantiate 0 Answers
Instantiate a prefab through code in C#. 4 Answers