Colin Stricker
Colin Stricker

Reputation: 25

Game Object Deleting Itself Prematurely

I am working through the Unity tutorials, and am currently on a tutorial called "Space Shooter." Something fishy has happened.

I noticed that the Boundary object, and the asteroid object both disappear when the game begins running. Note, both have colliders, and they are not touching. Their is a script called "DestroyByContact", which essentially destroys the game object whenever the player shoots it.

using UnityEngine;
using System.Collections; 

public class DestroyByBoundary : MonoBehaviour 
{ 
     void OnTriggerEnter(Collider other) 
     { 
           if (other.tag == "Boundary") 
           { 
                return; 
           } 

           Destroy(other.gameObject); 
           Destroy(gameObject); 
     } 
} 

I found that when I delete this script off of my Asteroid gameObject, the game functions normally, and the objects are deleted. Their must be something wrong with the script, but I cannot find out what went wrong.

EDIT: I forgot to place the Boundary object to the tag "Boundary" in Unity. This fixes the problem.

Upvotes: 1

Views: 475

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127563

Most likely you have not set or misspelled your boundary's tag Boundary1. See This point in the tutorial video.

This is causing your if (other.tag == "Boundary") to be false so it does not go in to the if block to exit the function early.

P.S.: If you are using Unity 5 you should now use if (other.CompareTag("Boundary")), it was not in Unity 4 when the space shooter tutorial was written and it supposedly has better performance than doing a other.tag == "Boundary" compare. You can see a example of it used in the Roll-A-Ball tutorial which is written in Unity 5. The Roll-A-Ball tutorial also has a example of adding a new custom tag in the Unity 5 UI.


1: Ironically I misspelled Boundary when I first posted this answer.

Upvotes: 1

Related Questions