- Home /
How do I end my game?
I am making a game where you play as an aliean spaceship and you have to avoid homing rockets, I want that if you hit the rocket you wait about 3 seconds and then the whole game stops, I want the program to close. I have been trying this for 2 days and I can't figure it out, I tried it myself and I used the internet but it won't work.
This is the code for the rocket: using System.Collections; using System.Collections.Generic; using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))] public class HomingMissle : MonoBehaviour {
public Transform target;
public float speed = 7f;
public float rotateSpeed = 200f;
public GameObject explosionEffect;
private Rigidbody2D rb;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate () {
Vector2 direction = (Vector2)target.position - rb.position;
direction.Normalize();
float rotateAmount = Vector3.Cross(direction, transform.up).z;
rb.angularVelocity = -rotateAmount * rotateSpeed;
rb.velocity = transform.up * speed;
}
void OnTriggerEnter2D ()
{
Instantiate(explosionEffect, transform.position, transform.rotation);
Destroy(gameObject);
Application.Quit();
}
}
And this is the code for the player/alien spaceship: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerController : MonoBehaviour {
public float moveSpeed;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetAxisRaw("Horizontal") > 0.5f || Input.GetAxisRaw("Horizontal") < -0.5f )
{
transform.Translate (new Vector3(Input.GetAxisRaw("Horizontal") * moveSpeed * Time.deltaTime, 0f, 0f));
}
if (Input.GetAxisRaw("Vertical") > 0.5f || Input.GetAxisRaw("Vertical") < -0.5f)
{
transform.Translate(new Vector3(0f, Input.GetAxisRaw("Vertical") * moveSpeed * Time.deltaTime, 0f));
}
}
}
Please help me, if you help me I will mention you in the game credits
Answer by finlay_morrison · Oct 20, 2017 at 07:57 PM
Firstly Application.Quit dosen't work in the unity editor and it onl works on some builds, it is generally frowned upon to use application.quit. However if you really want it to quit after 3 seconds here is how you do it
private void QuitAfterDelay(float time) {
Invoke("QuitApplication", time);
}
private void QuitApplication() {
Application.Quit();
}
Whenever you want to quit just call the QuitAfterDelay() function and inside the brackets put a float of how long you want to wait.
Hope this is what you wanted!
Thanks for your help but I get some errors, i'm trying to fix it.
Your answer
Follow this Question
Related Questions
Any Suggestions To Hide Terrain Borders? 3 Answers
Finishing game script c# 2 Answers
Animation syncronization trouble 1 Answer
Detect when animation starts/ends via script 1 Answer
I can't get a collision to cause the end of my game 1 Answer