NullReferenceException (635879)

Hello!
Hello. I have a wierd issue. This is the current code:

    void Cmd_Spawn(float X, float Y, float Z)
    {

            Debug.Log(X + " | " + Y + " | " + Z);
            Transform spawn = null;
            spawn.position = new Vector3(X, Y, Z);
            spawn.rotation = new Quaternion(0, 0, 0, 0);
            GameObject player = (GameObject)Instantiate (playerPrefab, spawn.position, spawn.rotation);
            posComponent.TeleportPosition(spawn.position);
            posComponent.TeleportRotation(spawn.rotation);


        
    }

So the issue is that the line:
spawn.position = new Vector3(X, Y, Z);
For some reason it prints out an error. However. At the line above that wich actually debug.logs the correct values.
Error message:
NullReferenceException: Object reference not set to an instance of an object
Spectator.Cmd_Spawn (Single X, Single Y, Single Z) (at Assets/Scripts/Spectator.cs:55)

Any clues?

You are trying to use a null transform reference “spawn” in pasted code. Assign “spawn” to the correct transform object to fix the error.

But I did set the position and rotation? Doesnt that make it assinged? Or am i missunderstanding this?

The Transform itself is null, you cannot use a null object because it doesn’t exist… Assigning position and rotation will not create a Transform.

OH. So I would do transform spawn = new Transform?

You should not use the “new” keyword to create Transforms. Create a public Transform field and assign an empty GameObject in your scene to it. Another option would be to skip the Transform altogether and just use a Vector3 for both the position and rotation.

Thanks alot. Got it all working.

You could probably get away with just the following:

void Cmd_Spawn(float X, float Y, float Z)
{
   Debug.Log(X + " | " + Y + " | " + Z);
   GameObject player = Instantiate(playerPrefab, new Vector3(X, Y, Z), Quaternion.identity) as GameObject;
   posComponent.TeleportPosition(player.transform.position);
   posComponent.TeleportRotation(player.transform.rotation);
}

With the code you provided I get a similar error:
NullReferenceException: Object reference not set to an instance of an object
Spectator.Cmd_Spawn (Single X, Single Y, Single Z) (at Assets/Scripts/Spectator.cs:59)
And line 59 is this:
netComponent.TeleportPosition(player.transform.position);

What is that about?

Either the player is failing to instantiate or “posComponent” is null.

AH. Thats the key. Found my issue. Thanks alot.