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:
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”.
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;
}
}