Help me destroy anplayer when out of bounds.
Hi. The project I am working on is a 2D platformer. I want to destroy my player if it falls down from a bridge. The max position of Y is -25 after which it would be destroyed and I will be back to my level selection screen. I wrote this code but it does not seem to function at all. Any help?
float outofbound = -25f;
if (gameObject.transform.position.y <= outofbound) {
Destroy(gameObject);
Application.LoadLevel("level");
}
Answer by NvGBoink · Nov 11, 2015 at 10:33 AM
This script seems to work just fine ? Here are a few things to check...
1) I know it's simple but I do it all the time, is the script attached to a gameobject ? 2) Do you have a scene saved under the name "Level" and is it set up in the build settings ? 3) Is this code ran in void Update ?
Yes I have made sure all of that is correct, the gameObject still doesn't get destroyed I don't know why.
Please can you share the whole script and the steps you have taken to setting it up ?
Answer by $$anonymous$$ · Dec 03, 2015 at 08:27 PM
Make a cube, turn off its visible mesh so its an invisible barrier and make it flat and place it at the level you want it. Name it Barrier, and create a tag and call it Barrier. Drag this scrip on it.
using UnityEngine;
using System.Collections;
public class DestroyByBoundary : MonoBehaviour
{
void OnTriggerExit(Collider other)
{
Destroy(other.gameObject);
}
}
You can also tweak it a bit and add it as
public GameObject explosion;
public GameObject playerExplosion;
void OnTriggerEnter(Collider other)
{
Instantiate(explosion, transform.position, transform.rotation);
if (other.tag == "Player")
{
Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
}
Destroy(other.gameObject);
}
}
so its more specific and it will add the explosion which you can also attach sound to as far as the particle you are using. It can be an explosion of blood if you have it, and a gross sound with it, or whatever you determine to make that explosion.
Note these come from the game tutorials and are simply modified by removing the useless and adding the useful bits of code,