application.loadlevel not working - c#

I am having trouble using the Application.LoadLevel from inside an if statement
Here is the code:
using UnityEngine;
using System.Collections;
public class Ritch: MonoBehaviour {
public bool dragging = false;
void Update () {
if (PreRitch.Deathritch == true)
{
transform.position = new Vector3(8f,6.89f,9f);
}
if (transform.position.x > 11.5 && dragging == false)
{
Application.LoadLevel(0);
}
else if (transform.position.x < 4.5 && dragging == false)
{
Application.LoadLevel(0);
}
}
void OnMouseDown()
{
dragging = true;
}
void OnMouseUp()
{
dragging = false;
}
}
The program is not loading the required level and if I put a print statement inside of one of the if statements nothing is printed.

Try to change code to:
using UnityEngine;
using System.Collections;
public class Ritch: MonoBehaviour {
public bool dragging = false;
void Update () {
if (PreRitch.Deathritch == true)
{
transform.position = new Vector3(8f,6.89f,9f);
}
//if (transform.position.x > 11.5 && dragging == false)
if (transform.position.x > 11.5f && dragging == false)
{
//Application.LoadLevel(0);
UnityEngine.SceneManagement.SceneManager.LoadScene(0);
}
//else if (transform.position.x < 4.5 && dragging == false)
else if (transform.position.x < 4.5f && dragging == false)
{
//Application.LoadLevel(0);
UnityEngine.SceneManagement.SceneManager.LoadScene(0);
}
}
void OnMouseDown()
{
dragging = true;
}
void OnMouseUp()
{
dragging = false;
}
}
You can use floats instead of doubles by adding f or F char

Related

Unity crashes when I destroy an object

I've made this code myself so I'm not sure what I've done wrong, I have a colider for my sword but whenever I get in range and swing my whole unity crashes
using System;
using UnityEngine;
public class Attack : MonoBehaviour
{
private CircleCollider2D cc2;
private float x = 3;
private Boolean timer = true;
private Boolean hasAttacked = false;
private void Start()
{
cc2.isTrigger = true;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(hasAttacked == false)
{
hasAttacked = true;
if (Input.GetKey(KeyCode.Mouse0))
{
while (timer == true)
{
x -= Time.deltaTime;
}
while (x >= 1)
if (collision.gameObject.name == "Enemy")
{
Destroy(GameObject.Find("Enemy"));
}
if (x == 0)
{
hasAttacked = false;
x = 3;
}
}
}
}
}
The Player is the parent of the sword if it makes a difference
It could be that they both try to destroy each other because the enemy is made to destroy the player
The problem is with the while (timer == true). If it's true, then it will stuck in there. Also when you decreasing x by Time.deltaTime, there is a little chance it will equals with 0, you should check with x <= 0.
Also you should check for input in Update.
I would save the reference of the enemy in OnCollisionEnter2D, and clear that in OnCollisionExit, and handle the attack in the Update. Something like that:
private GameObject _enemy;
private float _actCooldown = 3.0f;
private void Update()
{
if (Input.GetKeyDown(KeyKode.Mouse0) && _actCooldown <= 0.0f)
{
if (_enemy != null)
{
Destroy(_enemy);
_enemy = null;
}
_actCooldown = 3.0f;
}
_actCooldown -= Time.deltaTime;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name.Equals("Enemy")) _enemy = collision.gameObject;
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject == _enemy) _enemy = null;
}
Of course if there are more enemies, you'll have to add more logic to it.

OnCollisionExit() Not Working on my script unity?

I Am Working With Unity 3d and know little scripting and unity well. I Came To a point where I don't know what to do. My OnCollisionExit Don't Work on collision exit there is moment = true this dont work. Somebody told me you have not reset the variable. So I Don't Know How To Make It So Please Help. Thanks In Advance
This is The Player Script This Is My Script or code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Player : MonoBehaviour
{
public Animator anim;
public Transform housepos;
public Transform deadpos;
public static bool safe1_click = false;
public bool safe1_clicked = false;
public float speed = 25;
public Rigidbody rb;
Collider mycollider;
float Walk = 8;
float jump = 7;
float sadWalk = 6;
float idle = 0;
public static bool stopwalking = false;
public static bool Jump = false;
public static bool sadwalk = false;
public static bool freeze = false;
public static bool yourchance = false;
public static bool movement = true;
public bool movement23 = true;
// Start is called before the first frame update
void Start()
{
mycollider = transform.GetComponent<Collider>();
rb = GetComponent<Rigidbody>();
anim.SetFloat("Animation", Walk);
stopwalking = false;
Jump = false;
freeze = false;
}
// Update is called once per frame
void Update()
{
movement23 = movement;
if (movement == true)
{
safe1_click = safe1_clicked;
rb.velocity = new Vector3(speed * Time.deltaTime, rb.velocity.y, 0);
}
else
{
rb.velocity = new Vector3(0,0,0);
}
if (Jump == true)
{
anim.SetFloat("Animation", jump);
}
if (Jump == true)
{
anim.SetFloat("Animation", sadWalk);
}
if (stopwalking == true)
{
anim.SetFloat("Animation", idle);
}
}
public void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "stop")
{
Debug.Log("Stopped");
spawner.stopspawn = true;
movement = false;
return;
}
if (collision.gameObject.tag == "dec")
{
Debug.Log("oh");
freeze = true;
}
}
public void OnCollisionExit(Collision collision)
{
if (collision.gameObject.tag == "stop")
{
Debug.Log("Spawning");
spawner.stopspawn = false;
movement = true;
}
if (collision.gameObject.tag == "dec")
{
Debug.Log("oh");
freeze = false;
}
}
public void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "fre")
{
spawner.yourchance = true;
}
if (other.gameObject.tag == "Player")
{
Destroy(other.gameObject);
}
if (other.gameObject.tag == "dec")
{
freeze = true;
Debug.Log("oh");
}
if (other.gameObject.tag == "new")
{
yourchance = true;
Debug.Log("stopstop");
}
if (other.gameObject.tag == "con")
{
Debug.Log("collide happened");
movement = true;
}
}
private void OnTriggerExit(Collider other)
{
if(other.gameObject.tag == "dec")
{
freeze = false;
Debug.Log("oh");
}
}
}

UNITY3D c# Teleport object on certain amount of points

I encountered a problem with this code. The "Killer" teleports to the location and immediately goes back to the starting position. I have 7 locations for the "Killer" to teleport to (around the player). Whats wrong with this code? (I am a newbie) If possible could you add a sound to every point collected? example. When I get 1 points a sound/audio file plays. Thanks for answers!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FpsScoreScript : MonoBehaviour
{
public int points;
bool isTeleported1 = false;
bool isTeleported2 = false;
bool isTeleported3 = false;
bool isTeleported4 = false;
bool isTeleported5 = false;
bool isTeleported6 = false;
bool isTeleported7 = false;
bool isTeleported8 = false;
public GameObject Killer;
public GameObject Player;
public Transform Destination;
public Transform KillerDestFarBack;
public Transform KillerDestCloseBack;
public Transform KillerDestRight;
public Transform KillerDestLeft;
public Transform KillerDestRightFront;
public Transform KillerDestLeftFront;
public Transform KillerDestFront;
public void Update()
{
if (points == 1 && !isTeleported1)
{
Teleport1();
}
if (points == 2 && !isTeleported2)
{
Teleport2();
}
if (points == 3 && !isTeleported3)
{
Teleport3();
}
if (points == 4 && !isTeleported4)
{
Teleport4();
}
if (points == 5 && !isTeleported5)
{
Teleport5();
}
if (points == 6 && !isTeleported6)
{
Teleport6();
}
if (points == 7 && !isTeleported7)
{
Teleport7();
}
if (points == 8 && !isTeleported8)
{
Teleport8();
}
}
void Teleport1()
{
isTeleported1 = true;
Killer.transform.position = KillerDestFront.transform.position;
}
void Teleport2()
{
isTeleported2 = true;
Killer.transform.position = KillerDestRightFront.transform.position;
}
void Teleport3()
{
isTeleported3 = true;
Killer.transform.position = KillerDestLeftFront.transform.position;
}
void Teleport4()
{
isTeleported4 = true;
Killer.transform.position = KillerDestRight.transform.position;
}
void Teleport5()
{
isTeleported5 = true;
Killer.transform.position = KillerDestLeft.transform.position;
}
void Teleport6()
{
isTeleported6 = true;
Killer.transform.position = KillerDestFarBack.transform.position;
}
void Teleport7()
{
isTeleported7 = true;
Killer.transform.position = KillerDestCloseBack.transform.position;
}
void Teleport8()
{
isTeleported8 = true;
Player.transform.position = Destination.transform.position;
}
}
Instead of using many Transform vars, I would prefer using a transform array, also I have used an array of bools has teleported. I would prefer you to follow some tutorials or get a book. Add a collider to your player and the coin.
[SerializeField] Transform[] teleportPoints;
[SerializeField]Transform coin;
bool[] hasTeleported;
AudioSource source;
int points = 0 ;
void Awake()
{
source = GetComponent<AudioSource>();
hasTeleported = new bool[teleportPoints.Length];
}
private void Update()
{
for(int i = 0; i <= teleportPoints.Length; i++)
{
if (points == i && !hasTeleported[i])
{
Teleport(i);
}
}
}
void Teleport(int index)
{
transform.position = teleportPoints[index].position;
hasTeleported[index] = true;
}
void IncreasePoints()
{
source.Play();
points++;
}
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject == coin.gameObject)
{
IncreasePoints();
}
}

Unity HighScore Medals Like flappy bird

i am adding medals in my game like flappy bird, everything was working then i just stoped , and dont know what to do it gives me a error messege
NullReferenceException: Object reference not set to an instance of an object
ScoreManager.Start () (at Assets/scripts/ScoreManager.cs:27)
I`ve checked code lines and they were working fine until one moment ,with the same code.
But if i delete that object it shows me that the next isnt correct
Score script
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ScoreManager : MonoBehaviour
{
private float score = 0f;
public Text Scoretext;
public MenuController deathmenu;
public GameObject IntroGUI, DeathGUI, Canvas;
private GameObject bronze;
private GameObject bronzesilver;
private GameObject silver;
private GameObject silvergold;
private GameObject gold;
void Start()
{
bronze = GameObject.Find("bronze");
bronzesilver = GameObject.Find("bronzesilver");
silver = GameObject.Find("silver");
silvergold = GameObject.Find("silvergold");
gold = GameObject.Find("gold");
bronze.GetComponent<Image>().enabled = false;
bronzesilver.GetComponent<Image>().enabled = false;
silver.GetComponent<Image>().enabled = false;
silvergold.GetComponent<Image>().enabled = false;
gold.GetComponent<Image>().enabled = false;
}
void Update()
{
//handle back key in Windows Phone
if (Input.GetKeyDown(KeyCode.Escape))
Application.Quit();
if (GameStateManager.GameState == GameState.Intro)
{
if (WasTouchedOrClicked())
{
GameStateManager.GameState = GameState.Playing;
IntroGUI.SetActive(false);
Canvas.SetActive(true);
}
}
else if (GameStateManager.GameState == GameState.Playing)
{
score += Time.deltaTime;
Scoretext.text = ((int)score).ToString();
if (PlayerPrefs.GetFloat("Highscore") < score)
PlayerPrefs.SetFloat("Highscore", score);
if (score > 2)
{
bronze.GetComponent<Image>().enabled = true;
}
if (score > 4)
{
bronzesilver.GetComponent<Image>().enabled = true;
}
if (score > 7)
{
silver.GetComponent<Image>().enabled = true;
}
if
(score > 9)
{
silvergold.GetComponent<Image>().enabled = true;
}
if
(score > 12)
{
gold.GetComponent<Image>().enabled = true;
}
deathmenu.ToggleEndMenu(score);
}
}
void FixedUpdate()
{
//just jump up and down on intro screen
if (GameStateManager.GameState == GameState.Intro)
{
}
else if
(GameStateManager.GameState == GameState.Playing || GameStateManager.GameState == GameState.Dead)
{
}
}
bool WasTouchedOrClicked()
{
if (Input.GetButtonUp("Jump") || Input.GetMouseButtonDown(0) ||
(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))
return true;
else
return false;
}
void OnCollisionEnter2D(Collision2D col)
{
if (GameStateManager.GameState == GameState.Playing)
{
if (col.gameObject.tag == "CARS")
{
PlayerDies();
}
}
}
void PlayerDies()
{
GameStateManager.GameState = GameState.Dead;
DeathGUI.SetActive(true);
}
}

Using code in other class

My code works perfectly in the player class, but when I try to put it in a different class, it does nothing. My player doesn't lose lifes, and he doesn't die.
Here it doesn't work:
Spikes class
using UnityEngine;
using System.Collections;
public class Spikes : MonoBehaviour
{
SimplePlayer0 player = new SimplePlayer0();
Animator anim;
private bool isDead;
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "spike" && !isDead && player.Lives <= 1 && !player.IsImmune)
{
player.Lives = 0;
isDead = true;
}
else if (other.gameObject.tag == "spike" && player.Lives >= 1 && !player.IsImmune)
{
player.Lives--;
anim.SetBool("Immume", true);
player.IsImmune = true;
}
}
void OnTriggerStay2D(Collider2D other)
{
if (other.tag == "spike" && !isDead && player.Lives <= 1 && !player.IsImmune)
{
player.Lives = 0;
isDead = true;
}
else if (other.gameObject.tag == "spike" && player.Lives >= 1 && !player.IsImmune)
{
player.Lives--;
anim.SetBool("Immume", true);
player.IsImmune = true;
}
}
void OnCollisionStay2D(Collision2D other)
{
if (other.gameObject.tag == "spike" && !isDead && player.Lives <= 1 && !player.IsImmune)
{
player.Lives = 0;
isDead = true;
}
else if (other.gameObject.tag == "spike" && player.Lives > 1 && !player.IsImmune)
{
player.Lives--;
anim.SetBool("Immune", true);
player.IsImmune = true;
}
else if (other.gameObject.tag == "Underground")
{
isDead = true;
}
}
void Dead()
{
if (isDead == true)
{
Application.LoadLevel(8);
}
}
}
Player class
using UnityEngine;
using System.Collections;
public class SimplePlayer0 : MonoBehaviour
{
Animator anim;
//Lives
private int lives = 3;
private bool isImmune;
public float immuneCounter;
public float immuneTime;
//PROPERTIES
public int Lives
{
get { return lives; }
set { lives = value; }
}
public bool IsImmune
{
get { return isImmune; }
set { isImmune = value; }
}
void Start ()
{
anim = GetComponent<Animator>();
}
void Update()
{
if (IsImmune)
{
immuneCounter -= Time.deltaTime;
}
if (immuneCounter <= 0)
{
IsImmune = false;
immuneCounter = immuneTime;
anim.SetBool("Immume", false);
}
}
This was the original code where it did work:
using UnityEngine;
using System.Collections;
public class Player0 : MonoBehaviour
{
Animator anim;
//Lives
public int lives = 3;
public bool isImmune;
public float immuneCounter;
public float immuneTime;
public bool isDead;
void Start()
{
anim = GetComponent<Animator>();
}
void Update()
{
if (isImmune)
{
immuneCounter -= Time.deltaTime;
}
if (immuneCounter <= 0)
{
isImmune = false;
immuneCounter = immuneTime;
anim.SetBool("Immume", false);
}
if (isDead == true)
{
Application.LoadLevel(8);
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "spike" && !isDead && lives <= 1 && !isImmune)
{
rigidbody2D.velocity = Vector2.zero;
lives = 0;
rigidbody2D.AddForce(new Vector2(0, 200)); // death animation
isDead = true;
}
else if (other.gameObject.tag == "spike" && lives >= 1 && !isImmune)
{
lives--;
anim.SetBool("Immume", true);
isImmune = true;
}
}
void OnTriggerStay2D(Collider2D other)
{
if (other.tag == "spike" && !isDead && lives <= 1 && !isImmune)
{
rigidbody2D.velocity = Vector2.zero;
lives = 0;
rigidbody2D.AddForce(new Vector2(0, 200));
isDead = true;
}
else if (other.gameObject.tag == "spike" && lives >= 1 && !isImmune)
{
lives--;
anim.SetBool("Immume", true);
isImmune = true;
}
else if (other.gameObject.tag == "Underground")
{
rigidbody2D.AddForce(new Vector2(0, 200));
isDead = true;
}
}
void OnCollisionStay2D(Collision2D other)
{
if (other.gameObject.tag == "spike" && !isDead && lives <= 1 && !isImmune)
{
rigidbody2D.velocity = Vector2.zero;
lives = 0;
rigidbody2D.AddForce(new Vector2(0, 200));
isDead = true;
}
else if (other.gameObject.tag == "spike" && lives > 1 && !isImmune)
{
lives--;
anim.SetBool("Immune", true);
isImmune = true;
}
else if (other.gameObject.tag == "Underground")
{
rigidbody2D.velocity = Vector2.zero;
lives = 0;
isDead = true;
}
}
}
My guess is that your "Player" doesn't lose lives, because the object you're subtracting the lives from isn't your player. In your Spikes class, you're creating an all new Player object and decreasing the lives from that object, not your already available one.
What I would do, is have a GameController script, which instantiates the player (and anything else that may be required). That way, you know that you've only got one player object to work with.
For example:
public static class GameController
{
public static Player myOnlyPlayer; // either drag in the editor, or instantiate
}
Then you can use the following to access the object:
public class Spike
{
void OnCollisionEnter2D(Collision2D other)
{
// Do something with:
GameController.myOnlyPlayer.ReduceLifeCount();
}
}
Hope this helps!
Firstly - instantiating subclasses of MonoBehaviour via new is an error in itself - I am referring to SimplePlayer0 player = new SimplePlayer0(); in Spikes.cs. Don't do that.
Secondly - LokiSinclair's answer would work, but using a global variable for storing player and always applying the damage to it is very limiting. We should just check for what has collided with spikes and then decide what to do with it (mind you, my code isn't a really elegant solution either):
using UnityEngine;
using System.Collections;
public class Spikes : MonoBehaviour
{
private void ResolveDamage(Collision2D other){
if (other.gameObject.tag == "player"){
var player = other.gameObject.getComponent<SimplePlayer0>();
if(!player.IsImmune){
player.Lives--;
}
}
}
void OnCollisionEnter2D(Collision2D other)
{
ResolveDamage(other);
}
void OnTriggerStay2D(Collision2D other)
{
ResolveDamage(other);
}
void OnCollisionStay2D(Collision2D other)
{
ResolveDamage(other);
}
}
And your player logic should be contained in Player class - that's just a good design principle to follow:
using UnityEngine;
using System.Collections;
public class SimplePlayer0 : MonoBehaviour
{
Animator anim;
//Lives
private int lives = 3;
private bool isImmune;
public float immuneCounter;
public float immuneTime;
//PROPERTIES
//putting some logic in getters-setters of your properties
public int Lives
{
get { return lives; }
set {
if(lives != value){
lives = value;
if(IsDead){
Dead();
}else{
IsImmune = true;
}
}
}
}
private void Dead()
{
Application.LoadLevel(8);
}
public bool IsImmune
{
get { return isImmune; }
set {
if(isImmune != value){
isImmune = value;
anim.SetBool("Immume", isImmune);
//ternary operator - a shorthand for if-else statement
immuneCounter = isImmune ? immuneTime : 0;
}
}
}
public bool IsDead{
get{
return Lives <= 0;
}
}
void Start ()
{
anim = GetComponent<Animator>();
}
void Update()
{
if (IsImmune)
{
immuneCounter -= Time.deltaTime;
}
if (immuneCounter <= 0)
{
IsImmune = false;
}
}

Categories