Object Reference Not Set To An Instance Of An Object Unity

Posted on by admin
Object Reference Not Set To An Instance Of An Object Unity Average ratng: 5,0/5 2993 votes
  1. Object Reference Not Set To Instance Unity

I'm working on an adventure game in Unity and ran into this little bug. I'm trying to access a script within an instantiated object. Here is the related line of code:

Object reference not set to an instance of an object. NullReferenceException: Object reference not set to an instance of an object Unity.

From my understanding, the first line of code will create a Game Object called prefab2.The second line of code will allow me to access the component (A script) within prefab2.The third line will alter a variable within prefab2's script.

It seems logical to me, however I am getting a 'Object reference not set to an instance of an object' error.

Here are some details, if this helps find a solution.

Set
  1. If I just use Instantiate, and leave out the target.GetComponent, the prefab2 will spawn and will not give me any errors... In fact the Initialize script that is attached to prefab2 works just fine.

  2. I am calling the CastAbility function from an instantiated child object.

I've tried finding a solution for the last 4 hours, but to no avail.Any help would be appreciated.

LearnCocos2D
59.4k19 gold badges116 silver badges210 bronze badges
Brandon Stephen HaydenBrandon Stephen Hayden

1 Answer

I found the solution, the game object was being stored as a transform, rather than a game object. This had me confused because of a similar script I was running that also used a transform (Which worked just fine).

Brandon Stephen HaydenBrandon Stephen Hayden

Object Reference Not Set To Instance Unity

Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.

Not the answer you're looking for? Browse other questions tagged c#unity3druntime-error or ask your own question.

Posted by2 years ago
Archived

I am trying to disable a canvas then enable another one at the same time. I have the name 'Difficulty' spelled exactly the same in both the Hierarchy and the script but I keep on getting the error 'NullReferenceException: Object reference not set to an instance of an object MainMenuButtons.Update () (at Assets/Scripts/MainMenuButtons.cs:23)' One of the Canvas' disable but the other one won't enable. Here is the script. There is a comment on the line that the error occurs on.

5 comments