Missing reference exception: the object of type 'transform' has been destroyed.. error in unity

I’m getting error that’s object of type transform is destroyed how to clear it?

is that in a script?, are you destroying something then trying to use it?

if you could show the script, and copy the error thats in the console as it tends to indicate where the problem stemmed from and a little explanation on whats happening please.

… at first I created such that my player remains after he hits object then tried to destroy him and used destroy(gameobject); but I was using transform.position to stick camera with player.as it is destroyed now I’m continuosly getting this error how to solve it

Hi Pramo,

Please copy/paste your code and apply code formatting, screenshots are bad enough but a photo of a screen is really hard to read for those that are offering to help you. Please consider our eyes :eyes: :slight_smile:

Regarding your issue, if your camera has a reliance on the position of the player, you need to consider what you want to do when the player dies. For example, are they going to respawn somewhere else? If so, rather than calling Destroy you could just reduce the player lives and then move the player to the respawn position. The camera will then not have an issue with the object you are referencing it to being gone.

So, what do you want to happen when the player dies?


Updated Tue Oct 02 2018 14:02

Just another thought, if this is for the Red v Black game, you could consider having the camera as the player, but making the player’s avatar, e.g. the red sphere a child object of the camera. You’d put the player movement script on the camera, so it was directly changing the transform of the camera, the player’s avatar would effectively be dragged where the camera was moved, when the player’s avatar collides with something, you could then just destroy the child sphere, the camera would remain in place.

Note, you’d need a bit of an offset on the avatar, e.g. the distance between the sphere on the path and the camera above it.

This would also then allow for a respawn condition if the player has lives, you would then instantiate another player avatar (sphere) as a child of the camera and off you go again.


See also;

using UnityEngine;

public class PlayerCollision : MonoBehaviour {

    public PlayerMovement movement;

	void OnCollisionEnter(Collision collisionInfo)
    {
        
        if(collisionInfo.collider.tag == "obstacle")
        {
            movement.enabled = false;

            Debug.Log("daee");

            FindObjectOfType<GameManager>().EndGame();

            FindObjectOfType<Audiomanager>().play("playerdeath");

            Destroy(gameObject);
        }
    }
}
using UnityEngine;

public class FollowPlayer : MonoBehaviour {

    public Transform player;

    public Vector3 offset;
	// Update is called once per frame
	void Update () {
     
            transform.position = player.position + offset;


	}
}

so for this do i need to drag the player under camera and put the player movement script in the camera? if so i have another script playercollision what should i do that?

so for this do i need to drag the player under camera and put the player movement script in the camera?

It is certainly an option, but like most things, there will be many ways you could achieve what you want, which is why I suggested having a think about what is supposed to happen in your game when the player dies. For example, if they only get one life and then you are going to take them back to the main menu, none of this really matters, just load the main menu scene and all the objects in the previous scene will get destroyed anyway. But if you do want some form of respawning/restarting of the level, then yes, the above would be a way to accomplish that.

if so i have another script playercollision what should i do that?

Your script which is detecting the collision would be on the object that you want to detect the collision against, in this case, that isn’t the camera, it’s the player’s avatar, e.g. the sphere.

You could even consider a hierarchy like this;

  • Player
    • Main Camera
    • Avatar

In the above, your player movement script would be attached to the Player (created as an empty GameObject). The player input will now move the Player GameObject and all of those which are children of it.

The Main Camera would be dragged under Player to become a child.

The Avatar GameObject is your sphere, this is the GameObject which needs to know about collisions, so you could put your script on that.

Again, many ways to achieve the same thing. With the above, remember that the player will be moving the camera, so if you wanted that constrained to a specific location, with the player moving within that view, the above might not be the most appropriate solution.

so now i created a empty gameobject named it player dragged the player movement script under it… made the main camera and avatar as its child.the main camera has the follow player script and avatar as the player collision script.changed my camera position offset little bit longer about -7 on x axis… hit play.but now if my player is hit he’s not respawning or destroyed keeps on moving and when i try to move the whole thing rotates including ground and player flies away.did i do anything wrong?

The main camera won’t need a player follow script really now, as it is a child of the thing you are moving, so it will move with it.

Regarding the collisions, check you have your collision script on the avatar. If you are certain you do, place a Debug.Log statement at the top of the OnCollisionEnter method and see if the output appears in the console when you collide with an object.

Regarding the rotation, does your player movement allow rotation? I assumed, perhaps wrongly so, that your player movement was simply left and right, so changes to the X value of the transform for example.

using UnityEngine;

public class PlayerCollision : MonoBehaviour {

    public PlayerMovement movement;

	void OnCollisionEnter(Collision collisionInfo)
    {
        
        if(collisionInfo.collider.tag == "obstacle")
        {
            movement.enabled = false;

            Debug.Log("player hit");

            FindObjectOfType<GameManager>().EndGame();

            FindObjectOfType<Audiomanager>().play("playerdeath");

            Destroy(gameObject);
        }
    }
}

this is my player collision script used oncollisionenter and debug.log but when i hit object it does not shows anything…keeps on moving and not destroyed or respawned.i freezed the rotation of the player now the camera is not rolling but my player is passing some obstacles going through it and gets hit with some on some part player goes through the ground… it doesnt show anything when i hit the object but when i fall from the ground it shows message

Hey,

I will be back at my desk in about 40 minutes, if you can share your project files with me again I will be happy to take a quick look.

The forum will allow uploads of up to 10MB, if your project files (zipped) are larger than that you would need to use a service such as Google Drive or Dropbox, and then share the URL.

nice one Rob, alot quicker than me :slight_smile:
could always check to see if the player still exists in the camera follow script before trying to reference the player after its been destroyed…

 if (player != null)
            transform.position = player.position + offset;

or even if your going down the route of adding the camera as a child of the player.
before destroying the player, clear the parent of the camera.

Camera.main.transform.parent = null;

few different options, but im sure Rob has you covered :wink:

1 Like

https://drive.google.com/file/d/1EMzTtfjs_-LHxJAg3Ws3y95n9NaPvyl9/view?usp=drivesdk

Just added destroy(gameobject) in the player collision
Is there anyway to create a clone and destroy it by keeping actual player… I saw it in another forum

It’s not working used both… Still shows error

using UnityEngine;

public class FollowPlayer : MonoBehaviour {

public Transform player;

public Vector3 offset;
// Update is called once per frame
void Update () {

if(player !=null){

        transform.position = player.position + offset;

}

}

}

I’m grabbing your project now.

Just outline for me though what it is you want to achieve.

Do you want the camera to follow the path, e.g. straight down the road, regardless of player movement, the player would then effectively move left/right within that path, but the camera always stays in the centre, or, do you want the camera to follow the ball, so if the ball goes left, the camera goes left, if the ball falls off the path the camera follows it off too.

What do you want to happen when the player collides with an obstacle? You started off by destroying the player, so were you planning to respawn them somewhere (which I thought you were already doing in a previous version I looked at) or, is something else supposed to happen?

Please do apply code formatting when you copy/paste your code into your posts, it really helps us help you. :slight_smile:


See also;

Yes the camera wants to follow the player, to be moved along with the player at certain position behind it.at first i made to hit the object and nothing happens but now I made some changes thought to destroy player if it hits object and explode then respawn at starting position.but it shows error.and also need to learn how to make explosion effect after the player destroyed

Ok, I understand.

Project has just opened/updated, I’ll take a quick look now.

You know you have given me the same project files you gave me last time right? e.g. nothing that we’ve suggested above that you then said didn’t work? So I don’t actually see any errors, nor any errors from your original behaviour, e.g. when you destroyed the ball and the camera lost its transform reference.

Just want to check this is the right version to be looking at before I go too far on this.

This is the same file I sent you before but I made the changes that you told before and uploaded.i just want to clear this error nothing I changed except the destroy (gameobject) in the player collision.please if you don’t mind just add that and others all are same.i destroyed the player error shows up.as this is the same file it doesn’t have destroy (gameobject) that’s why you can’t see any error but if you add it.

Please don’t mistake me

Hi,

Sorry, I had a few other tasks to complete and was waiting for your reply.

Ok, so if you only want to resolve the error and nothing else then you need to make the following changes;

PlayerCollision.cs

void OnCollisionEnter(Collision collisionInfo)
{	
	if(collisionInfo.collider.tag == "obstacle")
	{
		movement.enabled = false;

		Debug.Log("daee");

		FindObjectOfType<GameManager>().EndGame();

		Destroy(gameObject);  // add this line back to destroy your game object
	}
}

FollowPlayer.cs

void Update () {
    if (player)  // check that player is not null before trying to access it to avoid NullReferenceException errors
    {
        transform.position = player.position + offset;
    }
}

Score.cs

void Update () 
{
    if (player) // check that player is not null before trying to use it to avoid a NullReferenceException error
    {
        scoreText.text = player.position.z.ToString("0");
    }
}

The above is based solely on the project you provided in the link above and will provide the following behaviour;

If you want to add explosions, you’ll need to add a Particle Effect component, or, instantiate a GameObject with a Particle Effect component at the point of destroying your player. Note, if you add the Particle Effect to the player and destroy it in the same way you are now, you’ll also destroy the Particle Effect and that will disappear also.

Some items you might want to consider before enhancing your project too much more;

  • be consistent with naming conventions “player”, “Directional Light”, “Canvas” - note the different case being used.
  • class names are typically capitalised, most of yours are with the exception of score.cs, credits.cs and menu.cs
  • obstacles - you have lots of these in your Hierarchy which makes finding things more difficult, you could parent them to one empty game object named “Obstacles” so you can collapse it to hide them
  • PlayerMovement.cs has an exposed field for the Rigidbody, but the script is on the same GameObject, you could instead use GetComponent<Rigidbody>() within your code to get this component
  • PlayerCollision.cs has an exposed field for the PlayerMovement.cs script component, you could instead use GetComponent<PlayerMovement>() within your code to get this component
  • you have a lot of public variables, presumably to expose them to the Inspector so you can change their values. If no other scripts need access to these, you could set them to be private and then use the [SerializeField] attribute to expose them in the Inspector

It is often worth investing in a little bit of housekeeping as you go along so that you don’t create a complicated project which in 6 months time you may not be able to navigate so easily.

Hope this helps. :slight_smile:


See also;

2 Likes

Thank you so much best ever forum I’ve visited… I’m in debt of gratitude with Ur help

2 Likes

You are very welcome Pramo, friendly bunch here.

Kudos to Daz (@OboShape) for jumping in to help also. :slight_smile:

1 Like

Privacy & Terms