- Home /
c# Destroy upon collision isn't working
I have runner who is supposed to destroy another game object "food" which is placed in my prefabs folder. Unfortunately, the code isn't working as expected. I would like to know what went wrong and how do I make the runner destroy "food" once the two collides?
I am attaching the screenshot of runner:
http://i59.tinypic.com/rqxcbc.jpg
This is the c# code of runner:
using UnityEngine;
using System.Collections;
public class runner : MonoBehaviour {
// The force which is added when the player jumps
// This can be changed in the Inspector window
public Vector2 jumpForce = new Vector2(0, 1);
// Use this for initialization
void Start () {
// destroy food upon collision
Destroy (GameObject.FindWithTag("food"),3);// 20sec
}
// Update is called once per frame
void Update () {
// Jump
if (Input.GetKeyUp("space"))
{
rigidbody2D.velocity = Vector2.zero;
rigidbody2D.AddForce(jumpForce);
}
// Die by being off screen
Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
if (screenPosition.y > Screen.height || screenPosition.y < 0)
{
Die();
}
}
// Die by collision
void OnCollisionEnter2D(Collision2D other)
{
Die();
}
void Die()
{
Application.LoadLevel(Application.loadedLevel);
}
}
Moreover, this is the screenshot of "food".
http://i57.tinypic.com/2dw7z10.png
This is the c# code of "food".
using UnityEngine;
using System.Collections;
public class foodpow : MonoBehaviour {
public Vector2 velocity = new Vector2(-4, 0);
// Use this for initialization
void Start()
{
rigidbody2D.velocity = velocity;
}
}
Answer by Andres-Fernandez · May 16, 2014 at 06:31 AM
Your code does a completely different thing. Placing
Destroy (GameObject.FindWithTag("food"),3);// 20sec
in your start function will destroy the first food object found 3 seconds after the start of the scene.
You should check for that in your OncollisionEnter2D function instead:
// Die by collision
void OnCollisionEnter2D(Collision2D other) {
if (other.gameObject.CompareTag("food")) {
Destroy (other.gameObject);
} else {
Die();
}
}
Also I'm not sure but this code might also kill the player when it touches the ground after jumping. In that case, check against the "floor" tag too (and if it's true then do nothing, just return).
Answer by motionlife89 · May 16, 2014 at 01:56 PM
@Andres Fernandez :
Thanks for responding to my question! Just a follow up questions though, when I debug the code, an error message appears at the last "}" in the code you posted saying " expected".
May I ask why I'm getting this error? I just copied the code you posted. should I retain this code or remove it instead?
void Die() { Application.LoadLevel(Application.loadedLevel); } }
If you want to reload the scene when you die, the code seems correct
void Die(){
Application.LoadLevel(Application.loadedLevel);
}
It looks like you have some syntax error. I suggest you check the code (and make sure each function has its curly brackets pair, and no semicolon is missed).