0

The following Unity 2D C# script loads the ScoreBoard scene about every third or fourth time run, but it should load the ScoreBoard scene every time run. Most of the time, it fails to load the scene. The object is to destroy any game object that collides with an empty game object that has a box collider. If a house collides with the collider, the house is destroyed and the ScoreBoard scene loads. (Most of the time, it doesn't load). Any advice is appreciated.

using UnityEngine;
using System.Collections;

public class DestroyObjectsOnGround : MonoBehaviour {

    void OnTriggerEnter2D(Collider2D collisionObject)
    {
        if (collisionObject.gameObject != null)
        {
            if (collisionObject.gameObject.tag == "house")
            {
                print ("house destroyed");
                Destroy (collisionObject.gameObject);

                Application.LoadLevel("ScoreBoard");
            } else {
                Destroy (collisionObject.gameObject);
            }
        }
    }
}
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
jadkins4
  • 903
  • 7
  • 18
  • 34

1 Answers1

0

Based on your comments, I guess you're moving the All-Destroying-Thing in a way that circumvents the physics engine.

If you use transform.position, you are teleporting the object. Anything between the old and new position will be ignored. As a result, collisions will not trigger properly.

The proper way is to apply a force to the object, set a velocity or use the method rigidbody2D.MovePosition().

If you use MovePosition() you should use it during FixedUpdate().

It is important to understand that the actual position change will only occur during the next physics update therefore calling this method repeatedly without waiting for the next physics update will result in the last call being used. For this reason, it is recommended that it is called during the FixedUpdate callback.

(source: manual)

Stefan Hoffmann
  • 3,214
  • 16
  • 30
  • Thanks. Actually, I am applying gravity to the object to let it fall and collide with the object that destroys the house. – jadkins4 Jul 19 '14 at 14:43
  • @jadkins4 How do you apply the gravity? Maybe add some code to your question. Is the object moving rather slow or pretty fast? – Stefan Hoffmann Jul 19 '14 at 17:28
  • Maybe it's wrong to say apply gravity, but I used house.rigidbody2D.isKinematic = false; – jadkins4 Jul 19 '14 at 20:38
  • Actually, using FixedUpdate() helped a lot. It only fails now about one of ten times played. – jadkins4 Jul 19 '14 at 20:39