Search code examples
unity-game-engineunityscriptgameobjectrigid-bodies

How do I get my terrain to self-delete?


I set up this code in the deletion script, first off:

var terrain = GetComponent(Rigidbody2D);

function Update ()
{
    if (terrain.position.x <= Camera.main.transform.position.x - 5)
    {
        Destroy(this.GameObject);
    }
}

Here is a picture of the screen:

enter image description here

And my prefab stuff:

enter image description here

What I want is for, when the camera is in front of the prefab, I want it to delete itself. However, this is the error I get:

NullReferenceException: Object reference not set to an instance of an object
UnityEngine.Component.GetComponent (System.Type type)
Deletion..ctor () (at Assets/Scripts/Deletion.js:3)
UnityEngine.Object:Instantiate(Object, Vector3, Quaternion)
Repeating Terrain:SpawnTerrain(Object) (at Assets/Scripts/Repeating Terrain.js:60)
Repeating Terrain:Update() (at Assets/Scripts/Repeating Terrain.js:52)

Solution

  • Try it with a timer and use console/debug to make sure you have the right object

     Destroy (this.GameObject, 5);
    

    or GameObject.Destroy(gameObject)