How to Fix NullReferenceException in C#! (4 Step Process)
HTML-код
- Опубликовано: 19 сен 2020
- Let's learn what is a NullReferenceException, what causes it and a Step-by-Step process for how to Fix NullReferenceException in C#!
🌍 FREE C# Beginner Complete Course! • Learn C# Beginner FREE...
🔴 Watch my Complete FREE Game Dev Course! 🌍 • Learn Unity Beginner/I...
🌍 Get my Complete Courses! ✅ unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
🌍 Get Code Monkey on Steam!
👍 Interactive Tutorials, Complete Games and More!
✅ store.steampowered.com/app/12...
If you have any questions post them in the comments and I'll do my best to answer them.
🔔 Subscribe for more Unity Tutorials / @codemonkeyunity
See you next time!
📍 Support on Patreon / unitycodemonkey
📦 Grab the Game Bundle at unitycodemonkey.com/gameBundl...
📝 Get the Code Monkey Utilities at unitycodemonkey.com/utils.php
#csharp #unitytutorial #unity3d
--------------------------------------------------------------------
Hello and welcome, I am your Code Monkey and here you will learn everything about Game Development in Unity 2D using C#.
I've been developing games for several years with 7 published games on Steam and now I'm sharing my knowledge to help you on your own game development journey.
You can see my games at www.endlessloopstudios.com
--------------------------------------------------------------------
- Website: unitycodemonkey.com/
- Twitter: / unitycodemonkey
- Facebook: / unitycodemonkey
🌍 FREE C# Beginner Complete Course! ruclips.net/video/pReR6Z9rK-o/видео.html
🔴 Watch my Complete FREE Game Dev Course! 🌍 ruclips.net/video/AmGSEH7QcDg/видео.html
🌐 Have you found the videos Helpful and Valuable?
❤️ Get my Courses unitycodemonkey.com/courses or Support on Patreon www.patreon.com/unitycodemonkey
Ķoķkķ kh l li
Yes
Yeah
Yeah, I agree
I am 15 years old. I have no CS Degree, nor any degree. I want to become a game developer. Can I become one?
THIS IS AWESOME! I just got stuck with this exception while trying to recreate everything I saw in your free course and my answer was here all along. really thank you the free course and these awesome videos.
Nice! I'm glad the video helped you! Keep on learning!
💬 I get a lot of questions on this error so I figured I'd make a video on what causes it and how I solve it!
How do YOU solve it? What is your process?
this is a classic standard error where you know 90% you forgot to pass something or to fill up the object with data...or 10% you disposed the object and its data when you shouldn't. still 100% human error. so there are a couple of tools while you are coding in vs by default that give you warnings about this...or you just read your exception detail stucktrace and you go directly where you should and you find the error and you fix it. nothing "special". just usual debugging. 🙄
One extra step that can be useful is to place the different parts of the line on "different lines". C# does not care if you go on a new line between keywords. And the debugger can show the exact line to quickly show what the offending variable was.
I am trying to use my strikepack on pc. Its been working perfectly for months but all of a sudden i keep getting error codes that say "an unhandled exception occured: system.NullReferenceException: Object reference not set to an instance of an object. at ScpControl.RootHub.OnDeviceArrival" how do i fix this? Is there anyway I can get on a phonecall or discord so I can share my screen. I really just need help with this.
Great video for people who is starting with programming.
Very well done. I will recommend this video to the beginners of C#. Congrats.
I am a beginner, i still found that tutorial useless, just attach an object! Haha
Very useful! You're the best!
Very nice explanation, I have seen this error a lot of times, and couldn't understand what was the problem. Thank you for your efforts!❤
Super helpful! Thank you!!
Thank you once again Code Monkey! This one took me longer to figure out but it was another simple mistake on my part.
This is great. Thank you so much for the teaching
Thank you so much! After like 2 days of troubleshooting, I figured out that my solution was 7:45
thanks a lot for this video simple and clear
Thanks for the help man :D
The lesson was super easy to understand and it helped me out a lot. Thanks! 💖
I'm glad it helped! Thanks!
Thank you this video helped me alot
Thank you! It was a really great video it could save me a lot of time) May be will save for smb else)
Thank you so much Code Monkey.
I'm glad you found it helpful!
Thanks alot. God bless you 🙏
Thank you so much!!!
very useful. thanks
thank you so much, you are the best ^^
In a couple of years i will probably look back to this moment and think what a noob i was. But thank you your video helped me solve my problem. :P
Life is a never ending learning journey! Keep at it!
Thanks!
very helpful I already know from people that it's about request an access to something that didnt exist but I don't know how to get over it... like where is the problem. This tutorial help me a lot
Thanks helped lot i became a fan!
Thanks!
Love love💙🖤😂thanks✨
Yes this video is very useful for us
Amazing :D
This would have been a good video to talk about Null-Coalescing and Null-Conditional-Operators as well. Maybe idea for future video?
Sooo helpful
Thanks
Helped Me Loads.
You will save the lives of so many noobs.
john es I used to think noob is an insult (I honestly thought it was a way for Runescape players to call you a nob without it being starred out to ***)!
@@gregoryfenn1462 it might be, but I think beginner is better
Great!
Debugging with a print command line is such a luxury!! Lots of low-level embedded C coding work won't even give you that information, if a memory address is wrong is corrupt or unset, then the CPU will do its best and either crash or behave in crazy ways without much guidance or any easy to use diagnostic tools. God I love C#!
I remember in college writing C going insane with the very unhelpful error "Segmentation Fault"!
Code Monkey I usually get “error at address 0x800000” and I’m like, so there’s an error in the software (that’s where the application launches from in our system). Haha. Fun times...
thank you so muchh
After watching your 16 min video i fixed my error in 1 min 😂
Thanks a lot ❤
Nice! And now next time it happens you will know what to do!
Hi @code Monkey.. I'm following your channel from recent times. Very helpful. I had seen your inventory system.but I wanted a different perspective. Can you make a video on horizontal scrolling inventory items , the scroll should also work with right and left scroll buttons. Also you should be able to drag the scrolling inventory items and drop over selling machine icon which is near by. ? Can you make a video? My kind request.
Look into the UI Scroll Rect object, helps you easily make a scrolling area.
Legend
tysm
Hey I have a 2d grid movement using tilemaps the player controller script takes a walkable tilemap and a collider tilemap for trees and rocks, the NullReferenceException happens on the walkable tilemap after the character takes his first step, both tilemaps show up on the PlayerController script in the the inspector though any idea whats going on?
Maybe the walkable tilemap was destroyed after the first step? Or maybe you're setting the reference again and this time it just grabs null?
I am trying to use my strikepack on pc. Its been working perfectly for months but all of a sudden i keep getting error codes that say "an unhandled exception occured: system.NullReferenceException: Object reference not set to an instance of an object. at ScpControl.RootHub.OnDeviceArrival" how do i fix this? Is there anyway I can get on a phonecall or discord so I can share my screen. I really just need help with this.
Thanks.
thx
I have this issue but I only have one variable and it does not debugprint as null it debugprints as the value I want
Very ueful Debug.Log tip idk how i didnt think of that
Test.
Do you heart comments?
thank you so much bro. next time i see u at the Krusty Krab your meals on me
ı have an error pls help me Assets\kodlar\CheckPoint.cs(31,28): error CS0029: Cannot implicitly convert type 'CheckPoint.TestObject' to 'LevelManager'
You cannot automatically convert one object of one type to a completely different type
Hi, so i get this error on my game when i change scenes. I have this button to change the scene with the code i learned from your videos "transform.Find("retryBtn").GetComponent().ClickFunc = () => { Loader.Load(Loader.Scene.Level1); };"
The "transform.Find("retryBtn") returns null on other scenes, i guess thats the error, but the game still works, and changes the scene.
That means that wherever you're running that script doesn't have a child named "retryBtn" in all your scenes.
Add Debug.Log(transform); to see which object has the script attached to it.
if the object is set to null and its suppose to hold a value after execution what am I suppose to do with it?
You look through the logic and see what part of your code isn't behaving as you think it should. There's no universal answer, it always depends on exactly what you're doing.
I think I have to watch this at least once a year.
Always useful to get a refresher!
hi im trying to understand why I am getting this null error I watched your video and tried the steps and I am still lost. the script is attached to my player cube.
it is using the new input system, and the input system generated a script that this code is pointing to so is that maybe the problem?
NullReferenceException: Object reference not set to an instance of an object
PlayerController.OnEnable () (at Assets/scripts/PlayerController.cs:15)
thanks in advance for any insight to this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField] private float speed, jumpSpeed;
private PlayerActionControls playerActionControls;
private void awake() {
playerActionControls = new PlayerActionControls();
}
private void OnEnable(){
Debug.Log(playerActionControls);
playerActionControls.Enable();
}
private void OnDisable() {
playerActionControls.Disable();
}
void Start()
{
}
// Update is called once per frame
void Update()
{
float movementInput = playerActionControls.land.move.ReadValue();
//move player
Vector3 currentPosition = transform.position;
currentPosition.x += movementInput * speed * Time.deltaTime;
transform.position = currentPosition;
}
}
You named your function "awake()" instead of "Awake()" so it's not being run by Unity automatically.
@@CodeMonkeyUnity omg!!! I new it was gonna be a case issue lol. Thanks so much loving your videos. Learning so much. Side note : Im a composer and musician so let me know if ever u need some original music!
i have the same error on the line audio1.playoneshot(audioclip) and i checked with debug.log so i noticed that audio1 is null....but i am assigning it in start method by audio1 = getcomponent(); so why null???
Probably because the object where you're running that script doesn't have a AudioSource component
@@CodeMonkeyUnity yeah sorry....forget to tell..in the start method instead of Start it was start so...that was dumb of me
How auto fill serilized field my both player and enemy have 30 serialised field every time create new scene I have to fill them up which takes time
You can make it into a prefab and fill in those fields just once. Although you can only set references that are in the Project Files.
I use try and catch
Hi, I have a problem when I'm doing your book Console. For example, no suggestions appear to me. If you can help me, I will be grateful to you
sorry my English not very good
Are you using Visual Studio? You should see Intellisense for the normal C# things and if you installed Visual Studio and Unity you should see it for Unity classes as well.
@@CodeMonkeyUnity can u make a video about this problems because I'm new in programming and don't know how to do that
@@CodeMonkeyUnity and yeah im using visual studio 2015 with unity
Please help I have this is issue but there is literally nothing wrong in the coding when I double click it in the console nothing comes up at all. The error message also only comes up when I start to record in the animation. the game is working as it should and says nothing in the console untill I start to animate what am I doing wrong?
Maybe you have a strange Unity error. Try resetting the layout and restarting Unity
@@CodeMonkeyUnity thanks do you know how to rest the layout?
@@randomisbest6234 On the upper right corner of the Unity window you see a button saying "Layout" click on it and there's an option to reset
@@CodeMonkeyUnity thanks for replying man it's said
failed the destroy editor windows #1 edit : just cleared the console went back to animation and it seams to of worked. Thank you so much man for replying so fast as well! subbed and liked!
prefix = prefix + stateMachine.name + ".";
do you know any meaning of this?
You're adding the stateMachine.name plus a . to whatever is on prefix
Hello Code Monkey
Every time when I build even an empty scene in WebGL module, unity throw 4 errors (like linker related error)
Please help
What errors?
@@CodeMonkeyUnity
// First Error
Failed running C:\Program Files\Unity 2019.3.7f1\Editor\Data\il2cpp\build/deploy/net471/UnityLinker.exe -out=C:/Users/Soham/Documents/Prototype/Temp/StagingArea/Data/Managed/tempStrip -x=C:/Users/Soham/AppData/Local/Temp/tmp6409ecf0.tmp -x=C:/Users/Soham/Documents/Prototype/Temp/StagingArea/Data/Managed/TypesInScenes.xml -d=C:/Users/Soham/Documents/Prototype/Temp/StagingArea/Data/Managed --include-unity-root-assembly=C:/Users/Soham/Documents/Prototype/Temp/StagingArea/Data/Managed/Assembly-CSharp.dll --include-unity-root-assembly=C:/Users/Soham/Documents/Prototype/Temp/StagingArea/Data/Managed/Unity.RenderPipelines.Core.Runtime.dll --include-unity-root-assembly=C:/Users/Soham/Documents/Prototype/Temp/StagingArea/Data/Managed/Unity.RenderPipelines.Universal.Runtime.dll --include-unity-root-assembly=C:/Users/Soham/Documents/Prototype/Temp/StagingArea/Data/Managed/UnityEngine.UI.dll --include-unity-root-assembly=C:/Users/Soham/Documents/Prototype/Temp/StagingArea/Data/Managed/Unity.TextMeshPro.dll --dotnetruntime=il2cpp --dotnetprofile=unityaot --use-editor-options --include-directory=C:/Users/Soham/Documents/Prototype/Temp/StagingArea/Data/Managed --rule-set=Conservative --editor-data-file=C:/Users/Soham/Documents/Prototype/Temp/StagingArea/Data/Managed/EditorToUnityLinkerData.json --platform=WebGL --enable-engine-module-stripping --engine-modules-asset-file="C:/Program Files/Unity 2019.3.7f1/Editor/Data/PlaybackEngines/WebGLSupport/Whitelists/../modules.asset"
stdout:
stderr:
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.
at Unity.Linker.UnityDriver..ctor(String[] args)
at Unity.Linker.Program.Main(String[] args)
UnityEngine.Debug:LogError(Object)
UnityEditorInternal.Runner:RunProgram(Program, String, String, String, CompilerOutputParserBase)
UnityEditorInternal.Runner:RunManagedProgram(String, String, String, CompilerOutputParserBase, Action`1)
UnityEditorInternal.AssemblyStripper:RunAssemblyLinker(IEnumerable`1, String&, String&, String, String)
UnityEditorInternal.AssemblyStripper:StripAssembliesTo(String, String&, String&, IEnumerable`1, UnityLinkerRunInformation)
UnityEditorInternal.AssemblyStripper:RunAssemblyStripper(UnityLinkerRunInformation)
UnityEditorInternal.AssemblyStripper:StripAssemblies(String, BaseUnityLinkerPlatformProvider, IIl2CppPlatformProvider, RuntimeClassRegistry, ManagedStrippingLevel)
UnityEditorInternal.IL2CPPBuilder:Run()
UnityEditorInternal.IL2CPPUtils:RunIl2Cpp(String, IIl2CppPlatformProvider, Action`1, RuntimeClassRegistry)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
// Second Error
Exception: C:\Program Files\Unity 2019.3.7f1\Editor\Data\il2cpp\build/deploy/net471/UnityLinker.exe did not run properly!
UnityEditorInternal.Runner.RunProgram (UnityEditor.Utils.Program p, System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser) (at :0)
UnityEditorInternal.Runner.RunManagedProgram (System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser, System.Action`1[T] setupStartInfo) (at :0)
UnityEditorInternal.AssemblyStripper.RunAssemblyLinker (System.Collections.Generic.IEnumerable`1[T] args, System.String& out, System.String& err, System.String linkerPath, System.String workingDirectory) (at :0)
UnityEditorInternal.AssemblyStripper.StripAssembliesTo (System.String outputFolder, System.String& output, System.String& error, System.Collections.Generic.IEnumerable`1[T] linkXmlFiles, UnityEditorInternal.UnityLinkerRunInformation runInformation) (at :0)
UnityEditorInternal.AssemblyStripper.RunAssemblyStripper (UnityEditorInternal.UnityLinkerRunInformation runInformation) (at :0)
UnityEditorInternal.AssemblyStripper.StripAssemblies (System.String managedAssemblyFolderPath, UnityEditorInternal.BaseUnityLinkerPlatformProvider unityLinkerPlatformProvider, UnityEditorInternal.IIl2CppPlatformProvider il2cppPlatformProvider, UnityEditor.RuntimeClassRegistry rcr, UnityEditor.ManagedStrippingLevel managedStrippingLevel) (at :0)
UnityEditorInternal.IL2CPPBuilder.Run () (at :0)
UnityEditorInternal.IL2CPPUtils.RunIl2Cpp (System.String stagingAreaData, UnityEditorInternal.IIl2CppPlatformProvider platformProvider, System.Action`1[T] modifyOutputBeforeCompile, UnityEditor.RuntimeClassRegistry runtimeClassRegistry) (at :0)
UnityEditor.WebGL.WebGlBuildPostprocessor.CompileBuild (UnityEditor.Modules.BuildPostProcessArgs args) (at /Users/builduser/buildslave/unity/build/PlatformDependent/WebGL/Extensions/Unity.WebGL.extensions/BuildPostprocessor.cs:387)
UnityEditor.WebGL.WebGlBuildPostprocessor.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args) (at /Users/builduser/buildslave/unity/build/PlatformDependent/WebGL/Extensions/Unity.WebGL.extensions/BuildPostprocessor.cs:929)
UnityEditor.Modules.DefaultBuildPostprocessor.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args, UnityEditor.BuildProperties& outProperties) (at :0)
UnityEditor.PostprocessBuildPlayer.Postprocess (UnityEditor.BuildTargetGroup targetGroup, UnityEditor.BuildTarget target, System.String installPath, System.String companyName, System.String productName, System.Int32 width, System.Int32 height, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at :0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
// Third Error
Build completed with a result of 'Failed' in 144 seconds (143677 ms)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
// Forth Error
UnityEditor.BuildPlayerWindow+BuildMethodException: 3 errors
at UnityEditor.BuildPlayerWindow+DefaultBuildMethods.BuildPlayer (UnityEditor.BuildPlayerOptions options) [0x002bb] in :0
at UnityEditor.BuildPlayerWindow.CallBuildMethods (System.Boolean askForBuildLocation, UnityEditor.BuildOptions defaultBuildOptions) [0x00080] in :0
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
Gautam Malakar OMG... sounds like a project setting not maybe windows path problem. Can you run and compile normal C# projects (try making a C# hello world command line application).
@@gregoryfenn1462 Yeah normal c# programs are working well
Even other modules (like pc Mac Linux android etc ) are working
Did he discover the dark arts!? O.o
#Code Monkey Hello. Thanks for the videos but they did not help me out yet to fix my script errors.
So here is summery of my story. I made a 2d project. Then I was asked to make it a 3d project for VR.
I made 3d project with same scripts and game Objects I was used in my 2d project. But Now I am getting Null Reference Errors for a line in my code.
I used a text object in 2d project which has changed to Text(TMP) in 3d project. I can not fix it. Can you please help me out on that?
Null reference has nothing to do with 2D or 3D, all the steps are the same regardless of how your camera is set up. Look into that line of code and see what could be null
Soo if i made a Refference to script how can it be null?
Depends on the context. Maybe you forgot to assign it, maybe you tried GetComponent but that game object doesn't have that component. Maybe the script has since been destroyed. Could be many different causes
@@CodeMonkeyUnity the script i was referring to was on a gameobject that was a prefab does it make some difference. It was an enemy who will be deleted after taking some damage. I can't show you my script because i deleted the unity project.
Why don't attach to Unity process instead of using Debug.Log? You've got to re-compile, and re-compile again after fixing (and do not forget all the Debug.Log places). Using Debug.Log is really a bad idea. See 'Debugging in Player' in docs (docs.unity3d.com/Manual/ManagedCodeDebugging.html)
I mention the Debugger in the end, personally I prefer using Debug.Log();
ill cashapp you or something i just really need help my controller isnt working and im a streamer so i need it to work. i could buy a new strikepack but i dont know if that will guareentee a fix so im hesitent
Sir This Is My full Error How I Can Solve This Problem. NullReferenceException: Object reference not set to an instance of an object
LevelProgressUI.GetDistance () (at Assets/Levels/Scripts/LevelProgressUI.cs:42)
LevelProgressUI.Start () (at Assets/Levels/Scripts/LevelProgressUI.cs:27)
Sir Please reply
Use Debug.Log to find what is null, follow the steps in the video
drive.google.com/file/d/1Idh8AaUmjDYGPnr8WzJoH0ycSx0mOHMR/view?usp=drivesdk
Sir please watch this video and please help me...
Sir please reply..
@@indiandev1588 Follow the steps in the video to find what is null, I cannot make your game for you
Good explanation, but I don't understand because I am dumb
What exactly don't you understand? The first step to understanding something is identifying exactly what you do or don't understand
Some times I wanding why I wach video that I know the answer
i double click and nothing happens
You can look in the stack trace message and go manually to that script and find that line
the problem with unity is unity causes those reference exceptions by default via the underlying platform. I just use LTS and without adding any extra code unity is still able to generate errors 🤣. Sometimes restarting unity bypasses/fixes those errors and mostly it doesn't.
Are you talking about a specific package or something? Unity will not randomly change a reference in your script
@@CodeMonkeyUnity I was talking about some low level running codes in UI toolkit and default input system. Unity didn't change any reference since it was a new project and I had no scripts yet but unity was still throwing me some null reference errors but these errors were just caused by some bugs that needs to be fixed in next LTS or beta version. Thanks for the reply. 👍
do you mind making a video about the new input system and ui toolkit integration. I couldn't seem to find any useful tips on internet that has integrated both with good examples.
@@altugozhan Sometimes there are some weird Layout or Editor window errors, they don't break anything so I normally just clear the console and continue working.
I covered the Input System here unitycodemonkey.com/video.php?v=Yjee_e4fICc but I haven't covered UI Toolkit yet
same here with the weird errors. Sometimes I restart and it clears the errors and sometimes not.
I already watched your input system tutorial video and it helped me a lot but couldn't integrate it into ui toolkit and couldn't find any good resources yet. Thanks again for your time.
Came here from an ad
I hope you like what you see!
Hi
Oh code monkey gave my comment a heart
What
2nd
1st
Simple. Don't reference non existing things.
I wanna marry you no homo
hello @CodeMonkey i'm still a beginner in game dev i followed this tutorial and thanks to you i was able to identify the error which was this: Debug.Log(GetComponent());
TextBox.GetComponent().text = "I need to get out of here!";
but now....i dont know what else to do can you please advice me on what step i should take to fix this bug
Not sure where you're running that code but you're checking if the object where you're running that code has a Text component, you're not testing if the object TextBox has a Text component.