The game is not restarting after the player dies - c#

I'm making this flappy bird replica but instead of a bird it's a rocket.
The controlls are different however the idea is the same.
I have setup a GameManager script:
using UnityEngine;
public class GameManager : MonoBehaviour
{
// Script Refrences
public BarrierSpawnner spawnner;
public MainMen menu;
public MoveLeft moveLeft;
public rockeyMovement movement;
void Start()
{
spawnner.StartedGame = false;
movement.dead = false;
spawnner.StartedGame = false;
movement.rend.enabled = true;
}
void Update()
{
if (spawnner.StartedGame)
{
menu.menuOn = false;
}
if (movement.dead == true)
{
spawnner.StartedGame = false;
}
if (spawnner.StartedGame == false)
{
menu.menuOn = true;
}
}
}
And a Movement Script:
using UnityEngine;
public class rockeyMovement : MonoBehaviour
{
// Variables
private float gravity;
private Vector2 startPos;
public bool dead;
// Refrences
public Rigidbody2D rb;
public BarrierSpawnner spawnner;
public Renderer rend;
public MainMen menStart;
public static rockeyMovement Instance { get; private set; }
void Start()
{
Instance = this;
startPos = transform.position;
rb = GetComponent<Rigidbody2D>();
gravity = rb.gravityScale;
rb.gravityScale = 0;
rend = GetComponent<Renderer>();
}
void OnCollisionStay2D(Collision2D collision)
{
dead = true;
gravity = rb.gravityScale;
rb.gravityScale = 0;
startPos = transform.position;
}
void Update()
{
if (spawnner.StartedGame)
{
rb.gravityScale = 2;
}
if (spawnner.StartedGame == false)
{
transform.position = new Vector2(0, 0);
}
Vector2 vel = rb.velocity;
float ang = Mathf.Atan2(vel.y, 10) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, ang - 90f));
if (Input.GetButton("Jump"))
{
rb.AddForce(Vector2.up * gravity * Time.deltaTime * 1000f);
}
}
}
As well as a MenuScript:
using UnityEngine;
public class MainMen : MonoBehaviour
{
public BarrierSpawnner spawnner;
public GameObject CanvasObject;
public bool menuOn;
void Update()
{
if (menuOn)
{
CanvasObject.GetComponent<Canvas> ().enabled = true;
}
}
public void Go()
{
spawnner.StartedGame = true;
CanvasObject.GetComponent<Canvas> ().enabled = false;
}
}
The game starts out normally in the correct way, the problems pop up the moment the player dies. When the player comes in contact with the obstacles I have the script set a bool to true "dead". And when "dead" is true the menu pops back again however, I you cannot interact with it and the page stays like that.
How do I fix this issue?
Is my logic right?
If not, where did I go wrong?

Don't disable Canvas component. Instead, create a panel with buttons on it and activate this panel when needed. Keep it deactivated otherwise.

Related

How to make the bullets to be firing towards a target?

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShootBullets : MonoBehaviour
{
public float bulletDistance;
public bool automaticFire = false;
public float fireRate;
public Rigidbody bullet;
private float gunheat;
private bool shoot = false;
private GameObject bulletsParent;
private GameObject[] startpos;
// Start is called before the first frame update
void Start()
{
bulletsParent = GameObject.Find("Bullets");
startpos = GameObject.FindGameObjectsWithTag("Fire Point");
}
private void Fire()
{
for (int i = 0; i < startpos.Length; i++)
{
Rigidbody bulletClone = (Rigidbody)Instantiate(bullet, startpos[i].transform.position, startpos[i].transform.rotation, bulletsParent.transform);
bulletClone.velocity = transform.forward * bulletDistance;
Destroy(bulletClone.gameObject, 0.5f);
}
}
// Update is called once per frame
void FixedUpdate()
{
if (automaticFire == false)
{
if (Input.GetMouseButtonDown(0))
{
Fire();
}
}
else
{
if (shoot == true)
{
Fire();
shoot = false;
}
}
if (gunheat > 0) gunheat -= Time.deltaTime;
if (gunheat <= 0)
{
shoot = true;
gunheat = fireRate;
}
}
}
now the bullets firing up the air and i want the bullets to fire to a target with physics.
the main goal later is to make some kind of side mission where the player third person view should shoot on object and if and when hitting the object the object will fall down and then the player will be able to pick it up.

How do I make my player speed up when collide with a game object in Unity?

I am doing a school project in Unity. My team and I decided to make an endless runner 2D game. However, because it is the first time I use C#, I don't know how to make my player's speed accelerate when collide with a game object in Unity. I only know how to destroy the player's health when a collision happens. Please help me! Thank you!
it's quite hard to give answers without seeing any code you've written, but as it's 2D and you've already got the collision damage working, you've probably used an OnCollisionEnter(), well it's very similar: you test if you've collided (which you've already done), then you add force to your player using a rigidbody2d, probably something along the lines of:
public Rigidbody2D rb;
void OnCollisionEnter2D(Collision2D collision)
{
rb.AddForce(direction * force, ForceMode2D.Impulse); // the ForceMode2D is
// optional, it's just so that
// the velocity change is sudden.
}
This should work.
If you have a GameManager that stores the game speed you can also do that too:
private float gameSpeedMultiplier = 0.5f;
void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.CompareTag("Tag of the collided object")
{
GameManager.Instance.gameSpeed += gameSpeedMultiplier;
}
}
public class PlayerContoler : MonoBehaviour
{
public static PlayerContoler instance;
public float moveSpeed;
public Rigidbody2D theRB;
public float jumpForce;
private bool isGrounded;
public Transform GroundCheckPoint;
public LayerMask whatIsGround;
private bool canDoubleJump;
private Animator anim;
private SpriteRenderer theSR;
public float KnockbackLength, KnockbackForce;
private float KnockbackCounter;
public float bonceForce;
public bool stopImput;
private void Awake()
{
instance = this;
}
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
theSR = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
if(!PauseMenu.instance.isPause && !stopImput)
{
if (KnockbackCounter <= 0)
{
theRB.velocity = new Vector2(moveSpeed * Input.GetAxis("Horizontal"), theRB.velocity.y);
isGrounded = Physics2D.OverlapCircle(GroundCheckPoint.position, .2f, whatIsGround);
if (isGrounded)
{
canDoubleJump = true;
}
if (Input.GetButtonDown("Jump"))
{
if (isGrounded)
{
theRB.velocity = new Vector2(theRB.velocity.x, jumpForce);
AudioManager.instance.PlaySFX(10);
}
else
{
if (canDoubleJump)
{
theRB.velocity = new Vector2(theRB.velocity.x, jumpForce);
canDoubleJump = false;
AudioManager.instance.PlaySFX(10);
}
}
}
if (theRB.velocity.x < 0)
{
theSR.flipX = true;
}
else if (theRB.velocity.x > 0)
{
theSR.flipX = false;
}
} else
{
KnockbackCounter -= Time.deltaTime;
if(!theSR.flipX)
{
theRB.velocity = new Vector2(-KnockbackForce, theRB.velocity.y);
} else
{
theRB.velocity = new Vector2(KnockbackForce, theRB.velocity.y);
}
}
}
anim.SetFloat("moveSpeed", Mathf.Abs(theRB.velocity.x));
anim.SetBool("isGrounded", isGrounded);
}
public void Knockback()
{
KnockbackCounter = KnockbackLength;
theRB.velocity = new Vector2(0f, KnockbackForce);
anim.SetTrigger("hurt");
}
}

How to change player speed with public float from another script

Hey I am trying to change a float when my player collides with a object. I tried many ways of reference but only got null when trying to debug I came up with this so far. I want to get the gameobject that contains the player script meaning the player and after I want to get the component script tankmovement to change the variable in it.
Getting the null reference error in the powerups script line 79 reset function Tank=GameObject.FindWithTag("Player")
using System.Collections.Generic;
using UnityEngine;
public class PowerUp : MonoBehaviour {
public bool boosting = false;
public GameObject effect;
public AudioSource clip;
public GameObject Tank;
private void Start()
{
Tank = GameObject.Find("Tank(Clone)");
TankMovement script = GetComponent<TankMovement>();
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
if (!boosting)
{
clip.Play();
GameObject explosion = Instantiate(effect, transform.position, transform.rotation);
Destroy(explosion, 2);
GetComponent<MeshRenderer>().enabled = false;
GetComponent<Collider>().enabled = false;
Tank.GetComponent<TankMovement>().m_Speed = 20f;
//TankMovement.m_Speed = 20f;
boosting = true;
Debug.Log(boosting);
StartCoroutine(coolDown());
}
}
private IEnumerator coolDown()
{
if (boosting == true)
{
yield return new WaitForSeconds(4);
{
boosting = false;
GetComponent<MeshRenderer>().enabled = true;
GetComponent<Collider>().enabled = true;
Debug.Log(boosting);
// Destroy(gameObject);
}
}
}
void reset()
{
//TankMovement.m_Speed = 12f;
TankMovement collidedMovement = Tank.gameObject.GetComponent<TankMovement>();
collidedMovement.m_Speed = 12f;
//TankMovement1.m_Speed1 = 12f;
}
}
}
Trying to call on my m_Speed float in the player script to boost the speed of my player when he collides with it. How would you get a proper reference since my player is a prefab.
Tank script
using UnityEngine;
public class TankMovement : MonoBehaviour
{
public int m_PlayerNumber = 1;
public float m_Speed = 12f;
public float m_TurnSpeed = 180f;
public AudioSource m_MovementAudio;
public AudioClip m_EngineIdling;
public AudioClip m_EngineDriving;
public float m_PitchRange = 0.2f;
private string m_MovementAxisName;
private string m_TurnAxisName;
private Rigidbody m_Rigidbody;
private float m_MovementInputValue;
private float m_TurnInputValue;
private float m_OriginalPitch;
private void Awake()
{
m_Rigidbody = GetComponent<Rigidbody>();
}
private void OnEnable ()
{
m_Rigidbody.isKinematic = false;
m_MovementInputValue = 0f;
m_TurnInputValue = 0f;
}
private void OnDisable ()
{
m_Rigidbody.isKinematic = true;
}
private void Start()
{
m_MovementAxisName = "Vertical" + m_PlayerNumber;
m_TurnAxisName = "Horizontal" + m_PlayerNumber;
m_OriginalPitch = m_MovementAudio.pitch;
}
private void Update()
{
// Store the player's input and make sure the audio for the engine is playing.
m_MovementInputValue = Input.GetAxis(m_MovementAxisName);
m_TurnInputValue = Input.GetAxis(m_TurnAxisName);
EngineAudio();
}
private void EngineAudio()
{
// Play the correct audio clip based on whether or not the tank is moving and what audio is currently playing.
if (Mathf.Abs(m_MovementInputValue) < 0.1f && Mathf.Abs(m_TurnInputValue) < 0.1f)
{
if (m_MovementAudio.clip == m_EngineDriving)
{
m_MovementAudio.clip = m_EngineIdling;
m_MovementAudio.pitch = Random.Range(m_OriginalPitch - m_PitchRange, m_OriginalPitch + m_PitchRange);
m_MovementAudio.Play();
}
}
else
{
if (m_MovementAudio.clip == m_EngineIdling)
{
m_MovementAudio.clip = m_EngineDriving;
m_MovementAudio.pitch = Random.Range(m_OriginalPitch - m_PitchRange, m_OriginalPitch + m_PitchRange);
m_MovementAudio.Play();
}
}
}
private void FixedUpdate()
{
// Move and turn the tank.
Move();
Turn();
}
private void Move()
{
// Adjust the position of the tank based on the player's input.
Vector3 movement = transform.forward * m_MovementInputValue * m_Speed * Time.deltaTime;
m_Rigidbody.MovePosition(m_Rigidbody.position + movement);
}
private void Turn()
{
// Adjust the rotation of the tank based on the player's input.
float turn = m_TurnInputValue * m_TurnSpeed * Time.deltaTime;
Quaternion turnRotation = Quaternion.Euler(0f, turn, 0);
m_Rigidbody.MoveRotation(m_Rigidbody.rotation * turnRotation);
}
}
Since the TankMovement component you need to access is attached to the GameObject that is colliding with the power, you can get the TankMovement component you need to change by using other.gameObject.GetComponent<TankMovement>():
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
if (!boosting)
{
// stuff
TankMovement collidedMovement = other.gameObject.GetComponent<TankMovement>();
collidedMovement.m_Speed = 20f;
// more stuff
}
}
}

How can i access another script function if the script to access is not attached to the same gameobject?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Teleport : MonoBehaviour {
public GameObject player;
public Camera mainCamera;
public Camera firstCam;
public Camera camera;
private List<GameObject> TeleportBooths;
private TeleportationsCore tc;
private void Start()
{
InstantiateObjects gos = GetComponent<InstantiateObjects>();
TeleportBooths = new List<GameObject>();
TeleportBooths = gos.PrefabsList();
firstCam.enabled = false;
mainCamera.enabled = false;
camera.enabled = true;
for (int i = 0; i < TeleportBooths.Count; i++)
{
TeleportBooths[i].AddComponent<TeleportationsCore>();
}
tc = GetComponent<TeleportationsCore>();
WorkingBooth();
}
private void WorkingBooth()
{
player.transform.position = TeleportBooths[tc.WorkingBooth()].transform.position;
camera.transform.position = new Vector3(TeleportBooths[tc.WorkingBooth()].transform.position.x - 10, TeleportBooths[tc.WorkingBooth()].transform.position.y + 10, TeleportBooths[tc.WorkingBooth()].transform.position.z);
camera.transform.LookAt(TeleportBooths[tc.WorkingBooth()].transform);
}
private void Update()
{
WorkingBooth();
}
}
I'm doing:
tc = GetComponent<TeleportationsCore>();
But tc is null.
And the script i want to access to:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TeleportationsCore : MonoBehaviour
{
public float spinSpeed = 2.0f;
private bool rotate = false;
private bool exited = false;
private int boothIndex = 0;
private void Start()
{
WorkingBooth();
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
Debug.Log("Player entered the hole");
rotate = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Player")
{
Debug.Log("Player exited the hole");
rotate = false;
exited = true;
}
}
void Rotate()
{
if (rotate)
{
if (spinSpeed == 350)
{
rotate = false;
exited = true;
boothIndex++;
WorkingBooth();
}
else
{
transform.Rotate(Vector3.up, spinSpeed * Time.deltaTime);
spinSpeed += 1f;
}
}
if (rotate == false && exited == true)
{
transform.Rotate(Vector3.up, spinSpeed * Time.deltaTime);
if (spinSpeed > 0.0f)
spinSpeed -= 1f;
}
}
public int WorkingBooth()
{
return boothIndex;
}
private void Update()
{
Rotate();
}
}
What i want is after i attach the script to all gameobject to get access the function WorkingBooth on TeleportationsCore.
And i don't want to attach the TeleportationsCore to the GameObject Teleport is attached on. So what other ways i have to access the WorkingBooth on TeleportationsCore ? Making the WorkingBooth public static ?
Change this:
for (int i = 0; i < TeleportBooths.Count; i++) {
TeleportBooths[i].AddComponent<TeleportationsCore>();
}
to:
TeleportationsCore[] tCores = TeleportBooths.Select(booth => booth.AddComponent<TeleportationsCore>());
Now just pick the core you want from the list.
Attach the TeleportationsCore script to empty game object. To get its reference, use this:
TeleportationsCore core = FindObjectOfType<TeleportationsCore>();
Use it for example in the Start function, as it is a bit slow.
You can find more in documentation.

Displaying and decrementing hp based on collision detection

So I have enemy gameobjects attacking a user in a small base. The enemies have an OnCollisionEnter method where it checks to see what it collides with. If it's tagged as the base, it sets an attack boolean to true, where the fixedupdate is supposed to check for that flag. When true, it calls a coroutine in which I try and call the method that removes health from the wall (this script is attached to the wall). The walls health is then displayed on a HUD I have elsewhere in the room Code Below
Problem is, enemies can't do damage to the base and the HUD remains unchanging. Any tips/help? Here is the enemy behaviour script
public class EnemyBehaviour : MonoBehaviour {
private GameObject target;
private Vector3 targetPos;
private WallBehaviour wallBehaviour;
public GameObject collisionObject;
private bool attackMode;
public float speed = 0.1f;
public int hp = 100;
public float attackCooldown = 1.0f;
public int attackPoints = 1;
public float killThreshhold = 1.5f;
public Color defaultColor;
//Use this for initialization
void Start() {
target = GameObject.FindGameObjectWithTag("MainCamera");
targetPos = target.transform.position;
attackMode = false;
}
void FixedUpdate() {
targetPos = target.transform.position;
transform.LookAt(target.transform);
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, targetPos, step);
if (attackMode)
{
StartCoroutine("attemptAttack");
}
else
{
GetComponent<Renderer>().material.color = defaultColor;
}
}
void OnCollisionEnter(Collision collision)
{
collisionObject = collision.gameObject;
if (collision.gameObject.tag == "Bunker") {
wallBehaviour = collision.gameObject.GetComponent<WallBehaviour>();
attackMode = true;
}
}
public IEnumerator Attack()
{
attackMode = false;
GetComponent<Renderer>().material.color = Color.red;
wallBehaviour.ProcessDamage(attackPoints);
yield return new WaitForSeconds(attackCooldown);
attackMode = true;
}
void ProcessDamage(int attackPoints)
{
hp -= attackPoints;
if (hp <= 0)
{
Die();
}
}
public int getHitPoints()
{
return hp;
}
public void Damage(DamageInfo info)
{
hp -= info.damage;
if (hp <= 0) {
Die();
}
}
public void Die()
{
Destroy(gameObject);
}

Categories

Resources