Home > Enterprise >  Non nullable field must contain a non-null value
Non nullable field must contain a non-null value

Time:10-17

So it's my first time with c# and i copied code to learn from it but when i copied it i had an error"Non nullable field must contain a non-null value..." we literally have the same code.

using System;
using UnityEngine;

namespace Trainer7dtd
{
    public class Loader
    {
        public static void Init()
        {
            Loader.Load = new GameObject();
            UnityEngine.Object.DontDestroyOnLoad(Loader.Load);
        }

        private static GameObject Load;
    }
}

private static GameObject Load; Load is where i get the error

CodePudding user response:

I believe the code that you copy was from previous version of .Net Core 5 or before which make an object reference GameObject Load to be allowed to be Null and set to Null by default.

But for .Net 6, it is no longer the case, you need to explicitly mention the object reference to be Nullable, by adding ? after the object reference declaration.

using System;
using UnityEngine;

namespace Trainer7dtd
{
    public class Loader
    {
        public static void Init()
        {
            Loader.Load = new GameObject();
            UnityEngine.Object.DontDestroyOnLoad(Loader.Load);
        }

        private static GameObject? Load;
    }
}

I hope this solve the problem. Cheers

  • Related