N
N
NeoLight32020-08-07 19:46:41
C++ / C#
NeoLight3, 2020-08-07 19:46:41

Object Reference not set to an instance of an object. What to do?

There is a function:

public static void CreatePNG(CommandArgs args)
        {
            try
            {
                GameObject _cam = new GameObject();
                var cam = UnityEngine.Object.Instantiate(_cam, new Vector3(args.sender.position.x + 10f, args.sender.position.y, args.sender.position.z), args.sender.rotation);
                ((GameObject)cam).camera.aspect = 1.0f;
                RenderTexture tempRT = new RenderTexture(512, 512, 24);
                ((GameObject)cam).camera.targetTexture = tempRT;
                ((GameObject)cam).camera.Render();
                RenderTexture.active = tempRT;
                Texture2D virtualPhoto = new Texture2D(512, 512, TextureFormat.RGB24, false);
                virtualPhoto.ReadPixels(new Rect(0, 0, 512, 512), 0, 0);
                RenderTexture.active = null;
                ((GameObject)cam).camera.targetTexture = null;
                byte[] bytes = virtualPhoto.EncodeToPNG();
                StreamWriter streamWriter = new StreamWriter("Unturned_Data/Managed/picture.png", true);
                streamWriter.Write(bytes);
                streamWriter.Close();
                Reference.Tell(args.sender.networkPlayer, "Successfully created Picture!");
                UnityEngine.Object.DestroyObject(cam);
            }
            catch (Exception err)
            {
                Reference.Tell(args.sender.networkPlayer, $"Err: {err.Message}");
            }
        }


When it is executed, an error occurs Object Reference not set to an instance of an object, I looked for solutions on the Internet - I did not find it.
Where did I make a mistake?
What I'm doing:
In my function, I want to create a new game object in the Unity scene,
which I then instantiate, and then I try to render a photo from the camera of this object.
What am I doing wrong ?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question