To restart the game on a button click in unity framework - unity3d

this is my code
void Start () {
GetComponent<SpriteRenderer>().enabled = false;
animator = transform.GetComponentInChildren<Animator>();
if (animator == null) {
Debug.LogError("Didn't find animator");
}
}
}
GetComponent<Rigidbody2D>().AddForce(Vector2.right * forwardSpeed);
if (didFlap) {
GetComponent<Rigidbody2D>().AddForce (Vector2.up * flapSpeed);
animator.SetTrigger("Doflap");
didFlap = false;
time = 0;
}
// Do graphics & input update
void Update(){
if(Input.GetKeyDown(KeyCode.Space) || (Input.GetMouseButtonDown(0))){
didFlap=true;
}
}
public void TakeDamage(float tim) {
Application.LoadLevel(Application.loadedLevel);
}
// Do physics engine update
void FixedUpdate () {
if (dead) {
Time.timeScale = 0;
GetComponent<SpriteRenderer>().enabled = true;
if(Time.timeScale == 0 && (Input.GetKeyDown (KeyCode.Space) || Input.GetMouseButtonDown (0))){
Application.LoadLevel(Application.loadedLevel);
here when i give the line(Application.LoadLevel(Application.loadedLevel);) with out if the game restarts.but when i give inside the if its not working..on the game dead i set the Time.timeScale to 0,and a restart button appears on the screen.on a touch again i need to restart.but when i gave the code for restart inside the if its not working,when i give it with out if the game suddenly restarts after dead with out giving a space to click the restart button.
i need to restart on the button click
}
}
void OnCollisionEnter2D(Collision2D collision){
animator.SetTrigger("Death");
dead = true;
}
}

When you set the TimeScale to 0, your Inputs will also stop working as they are dependant on the actual Time ;-) You could however still use the Input.GetAxisRaw to achieve similar goal. As it is not depending on the TimeScale.
But a better solution is to just add a UI Button that are available in unity 4.6+, using their new built in UI.

Related

How do I make the 2D collider not do any function to already colliding objects before level start

In my level, I have a water collider where if you fall in, it triggers a splash effect and water sounds. However, because there is already an object inside the water, whenever I start the level, the water collider triggers and splash and water sounds despite the object already being in the collider.
So, even with the object deep inside the water collider, it creates the splash sound and water effect as if it just fell in.
How do I prevent this?
My code involves OnTrigger2D functions. But how do I make Unity check if an object is already colliding before level load?
Code:
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
gravityoriginal = playerrigidbody.gravityScale;
massoriginal = playerrigidbody.mass;
playerrigidbody.gravityScale = 0.1f;
playerrigidbody.mass = other.GetComponent<Rigidbody2D>().mass + 2f;
splash.Play(); //Plays the initial splash if velocity is high
underwaterbool.IsUnderwater = true; //stop dust particle
mainmusic.enabled = true;
powerupmusic.enabled = true;
deathmusic.enabled = true;
}
else if (other.tag == "Snatcher")
{
masssnatcheroriginal = snatcherrigidbody.mass;
gravityoriginalsnatcher = snatcherrigidbody.gravityScale;
snatcherrigidbody.gravityScale = 0.1f;
snatcherrigidbody.mass = other.GetComponent<Rigidbody2D>().mass + 2f;
splashsnatcher.Play();
snatchersounds.enabled = true;
}
else if (other.tag != "Player" && other.tag != "Snatcher" && other.GetComponent<Rigidbody2D>() != null)
{
gravityoriginalbox = other.GetComponent<Rigidbody2D>().gravityScale;
massoriginalbox = other.GetComponent<Rigidbody2D>().mass;
other.GetComponent<Rigidbody2D>().mass = other.GetComponent<Rigidbody2D>().mass + 2f;
other.GetComponent<Rigidbody2D>().gravityScale = 0.1f;
other.GetComponent<ParticleSystem>().Play(false);
splashaudio.Play();
Splashparticlesforbox.IsUnderwaterBox = true;
}
if(other.GetComponent<Rigidbody2D>() != null)
{
other.GetComponent<Rigidbody2D>().velocity = new Vector2(0f, -0.5f);
}
if (!cooldown)
{
splashaudio.Play();
}
cooldown = true;
StartCoroutine(waittime());
}
Can you post your OnTrigger2D functions code please? Normally Unity does not trigger the OnTriggerEnter method if an object is already inside the trigger when the scene beggins but the OnTriggerStay is executed every frame.
Anyway... one option (not the best one I think) would be to put a boolean propoerty in the trigger that is initialized true and use it to prevent the OnTriggerFunctions to do anything til the fame ends. Then in the LateUpdate method you can set the property as false.
bool m_FirstFrame = true;
void onEnable()
{
m_FirstFrame = true;
}
void OnTriggerEnter2D(Collider2D collision)
{
if(m_FirstFrame){
return;
}
.... //Rest of code
}
//Same for the other OnTrigger2D methods you use
void LateUpdate()
{
m_FirstFrame = false;
}
I hope it helps! Tell me if you need something more, and please, post your code, that way is easier for us to fint where is the issue and get how to fix it.
Good luck ^^

WaitForSeconds function not displaying correctly

I'm working on a laser that fires for a set amount of time before switching off.
I am using WaitForSeconds calling the fire function, waiting for x seconds and then turning it off.
I can see it working by turning the colliders and sprites on and off in the Unity menus, but they never physically appear in the game; whereas without the code they do appear.
void Start()
{
StartCoroutine(LaserTimer());
}
void LaserFire()
{
beamCollider.enabled = true;
beamSprite.enabled = true;
}
void StopFire()
{
beamCollider.enabled = false;
beamSprite.enabled = false;
}
IEnumerator LaserTimer()
{
LaserFire();
yield return new WaitForSeconds(5);
StopFire();
yield return new WaitForSeconds(5);
}

Stopping the update function in Unity

I have some code that when it executes, it pushes a character forward. The issue is that the character never stops moving and continues forever. Is there a way to stop the character from moving after 2 seconds? Here is the code I'm using:
public class meleeAttack : MonoBehaviour
{
public int speed = 500;
Collider storedOther;
bool isHit = false;
void Start()
{
}
void Update()
{
if (isHit == true )
{
storedOther.GetComponent<Rigidbody>().AddForce(transform.forward * speed);
}
}
void OnTriggerStay(Collider other)
{
if (other.gameObject.tag == "Player" && Input.GetKeyUp(KeyCode.F))
{
storedOther = other;
isHit = true;
}
}
}
I'm not sure if there's a way to stop the update() function so it stops the character movement.
The Update function is part of the life cycle of a Unity script. If you want to stop the Update function to be executed, you need to deactivate the script. For this, you can simply use:
enabled = false;
This will deactivate the execution of the life cycle of your script, and so prevent the Update function to be called.
Now, it looks like you are applying a force to your character to make it move. What you might want to do then is, after two seconds, remove any force present on your character. For that, you can use a coroutine, which is a function that will not just be executed on one frame, but on several frames if needed. For that, you create a function which returns an IEnumerator parameter, and you call the coroutine with the StartCoroutine method:
bool forcedApplied = false;
void Update()
{
if (isHit == true && forceApplied == false)
{
storedOther.GetComponent<Rigidbody>().AddForce(transform.forward * speed);
forceApplied = true;
StartCoroutine(StopCharacter);
isHit = false;
}
}
IEnumerator StopCharacter()
{
yield return new WaitForSeconds(2);
storedOther.GetComponent<Rigidbody>().velocity = Vector3.zero;
forceApplied = false;
}
Those might be different ways to achieve what you want to do. It's up to you to choose what seems relevant to your current gameplay and to modify your script this way.

Showing/Hiding Banners in Unity 5.1 and AdMob plugin 2.3 after some time won't hide banner or even load it, any idea why?

I integrated AdMob in my Unity project where banners are supposed to be displayed at menu and game over screen. Problem is that after some time banner ether wont hide any more or stops from showing up.
Here is a code for requesting and showing/hiding banners:
bool bannertrigger = false;
public float bannerRequestTimeout;
float bannerRequestedTime;
float bannerSakrivanjeVreme;
void Start(){
RequestBanner();
bannerRequestedTime = Time.time;
}
void Update(){
if (Time.time > bannerRequestedTime + bannerRequestTimeout) {
RequestBanner ();
bannerRequestedTime = Time.time;
}
if ((GameController.pause || GameController.gameOver !=0) && !bannertrigger) {
bannerView.Show ();
bannertrigger = true;
Debug.Log (bannertrigger);
}
if (!GameController.pause && GameController.gameOver == 0 && bannertrigger) {
bannerView.Hide();
bannertrigger = false;
Debug.Log (bannertrigger);
}
}
}
Debug log shows that if statements works like they are supposed to do, so the problem is somewhere in bannerView.Show() and bannerView.Hide() but I have no idea what to do anymore. What am I doing wrong?
GameController.pause is bool (true if paused)
GameController.gameOver is int (!= 0 if game over)

Unity3D scene not working properly and lagging after reloading

I have looked all over internet, but I cannot find a solution to my problem. I am trying to create a game and it has 3 scenes: the Game Start, Main and Game over.
The problem is that when trying to load the main level from other scenes it does not do what it has to do (e.g. jump) and the scene itself is lagging. When I try to load only the Main Scene it works ok, but after the character dies and the scene is reloaded, it starts to lag again and I cannot jump or do anything it is supposed to do.
Any ideas on what the problem might be?
using UnityEngine;
using System;
public class Player : MonoBehaviour
{
// The force which is added when the player jumps
// This can be changed in the Inspector window
public Vector2 jumpForce = new Vector2(0, 300);
private bool shouldJump = true;
// Update is called once per frame
private float jumpThreshold = 0.5f;
private float previousJumpTime;
void FixedUpdate ()
{
// Jump
float mc = MicControl.loudness;
//Debug.Log (mc);
if (mc>1.3f && shouldJump)
{
shouldJump = false;
previousJumpTime = Time.time;
GetComponent<Rigidbody2D>().velocity = Vector2.zero;
GetComponent<Rigidbody2D>().AddForce(jumpForce);
}
if (!shouldJump)
{
if(Time.time-previousJumpTime>jumpThreshold)
{
shouldJump = true;
}
}
// 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 ("main");
}
}
You said your level is called Main, but in the code you are loading "main", i'm not sure if that's the problem, but you seem to be loading the level correctly, so check if is main or Main the exact name of the level.
Also, when compiling, make sure you have all levels checked
With provided data its impossible to say what causes low performance, but I recommend you to use Profiler tool (can be found in personal version of Unity 5) and figure out what scripts and functions are problematic.
Also, try to avoid calling GetComponent<Rigidbody2D>() in Update/FixedUpdate/LateUpdate and cache this component instead.
I second what Utamaru said.
Rigidbody2D myRigidbody2d;
void Start ()
{
myRigidbody2d = GetComponent<Rigidbody2D>(); //Do this once
}
Inside your fixed update, you can do this:
void FixedUpdate ()
{
// Jump
float mc = MicControl.loudness;
//Debug.Log (mc);
if (mc>1.3f && shouldJump)
{
shouldJump = false;
previousJumpTime = Time.time;
myRigidbody2d.velocity = Vector2.zero;
myRigidbody2d.AddForce(jumpForce);
}
if (!shouldJump)
{
if(Time.time-previousJumpTime>jumpThreshold)
{
shouldJump = true;
}
}
// Die by being off screen
Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
if (screenPosition.y > Screen.height || screenPosition.y < 0)
{
Die();
}
}
I can't see the rest of your code so I am not really sure that is the problem but give this a try.