creating a Breakout game in unity3d c#-bricks wont get destroyed - c#

I have made a breakout game using unity tutorials and everything seemed to work well, but when I played it in the game mode there were some errors. So after I tried fixing the errors, the bricks wont get destroyed anymore. I tried undoing it, writing the code anew or even writing the same project anew but nothing works. What can I do?
These are the codes for my game which are exactly like the codes in the tutorial!
Paddle:
public class Paddle : MonoBehaviour {
public float paddleSpeed = 1f;
private Vector3 playerPos = new Vector3(0, -9f, 0);
void Update ()
{
float xPos = transform.position.x + (Input.GetAxis("Horizontal")*paddleSpeed);
playerPos = new Vector3(Mathf.Clamp(xPos, -7.5f, 7.5f), -9f, 0f);
transform.position = playerPos;
}
}
Ball:
public class Ball : MonoBehaviour {
private float ballInitialVelocity = 600f;
private Rigidbody rb;
private bool ballInPlay;
void Awake ()
{
rb = GetComponent<Rigidbody>();
}
void Update ()
{
if(Input.GetButtonDown("Fire1") && ballInPlay==false)
{
transform.parent = null;
ballInPlay = true;
rb.isKinematic = false;
rb.AddForce(new Vector3(ballInitialVelocity, ballInitialVelocity, 0));
}
}
}
GM:
using UnityEngine; using System.Collections;
public class deathZone : MonoBehaviour {
void OnTriggerEnter(Collider col)
{
GM.instance.loseLife();
}
}
public class GM : MonoBehaviour {
public int Lives = 3;
public int bricks = 16;
public float resetDelay = 1f;
public Text livesText;
public GameObject gameOver;
public GameObject bricksPrefab;
public GameObject youWon;
public GameObject paddle;
public GameObject deathParticles;
public static GM instance = null;
private GameObject clonePaddle;
void Start()
{
if (instance == null)
instance = this;
else if (instance != this)
instance = null;
setup();
}
public void setup()
{
clonePaddle = Instantiate(paddle, new Vector3(0, -9,0), Quaternion.identity) as GameObject;
Instantiate(bricksPrefab, new Vector3((float)18.5, (float)-61.14095, (float)238.4855), Quaternion.identity);
}
void checkGameOver()
{
if (bricks < 1)
{
youWon.SetActive(true);
Time.timeScale = .25f;
Invoke("Reset", resetDelay);
}
if (Lives < 1)
{
gameOver.SetActive(true);
Time.timeScale = .25f;
Invoke("Reset", resetDelay);
}
}
void Reset()
{
Time.timeScale = 1f;
Application.LoadLevel(Application.loadedLevel);
}
public void loseLife()
{
Lives--;
livesText.text = "Lives: " + Lives;
Instantiate(deathParticles, clonePaddle.transform.position, Quaternion.identity);
Destroy(clonePaddle);
Invoke("SetupPaddle", resetDelay);
checkGameOver();
}
void SetupPaddle()
{
clonePaddle = Instantiate(paddle, new Vector3(0, -9, 0), Quaternion.identity) as GameObject;
}
public void destroyBrick()
{
bricks--;
checkGameOver();
}
}
Bricks:
public class Bricks : MonoBehaviour {
public GameObject brickParticle;
void OnCollisionEnter(Collision other)
{
Instantiate(brickParticle, transform.position, Quaternion.identity);
GM.instance.destroyBrick();
Destroy(gameObject);
}
}
deathZone:
public class deathZone : MonoBehaviour {
void OnTriggerEnter(Collider col)
{
GM.instance.loseLife();
}
}

In this tutorial you have to make sure all of the bricks GameObject have both the Bricks script and a BoxCollider components. Also the ball should have a Rigidbody and a SphereCollider components.
An easy way to debug Collisions or Triggers is to simply use a Debug.Log("something"); as a first command in the OnCollisionEnter/OnTriggerEnter/... methods.

It seems that the issue is with colliders. You should check them in Editor if they are placed right ( since no debug.log on collision is written). Also make sure that you are using Colliders and not colliders2D ( collision is called by diffrent method)

Related

The Spawned enemy only moves, but not shoots in unity

I am new to unity. Recently, I have started making a survival fps game, there, I have 1 enemy, when I kill him, it will spawn more enemies. However, the spawned only move, but not shoot. Although, I have attached a script to it. here are all my code.
prefab_shooting-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class prefab_shooting : MonoBehaviour
{
public float damage = 1f;
public float range = 100f;
public GameObject player;
public GameObject enemy;
private void Start()
{
player = GameObject.FindWithTag("Player");
enemy = GameObject.FindWithTag("PBR");
}
private void Update()
{
if (Vector3.Distance(transform.position, player.transform.position) < 25.0f)
{
Debug.Log(damage);
}
}
void Shoot()
{
RaycastHit hit;
if (Physics.Raycast(enemy.transform.position, enemy.transform.forward, out hit, range))
{
if (hit.transform.tag == "Player")
{
swat_death swat = hit.transform.GetComponent<swat_death>();
// Debug.Log(damage);
}
}
}
}
PBR_shooting (the enemy shooting)-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PBR_shooting : MonoBehaviour
{
public float damage = 1f;
public float range = 100f;
public GameObject player;
public GameObject enemy;
private void Start()
{
player = GameObject.FindWithTag("Player");
enemy = GameObject.FindWithTag("PBR");
}
private void Update()
{
if (Vector3.Distance(transform.position, player.transform.position) < 25.0f)
{
Shoot();
}
}
void Shoot()
{
RaycastHit hit;
if(Physics.Raycast(enemy.transform.position, enemy.transform.forward, out hit, range))
{
if(hit.transform.tag == "Player")
{
swat_death swat = hit.transform.GetComponent<swat_death>();
// Debug.Log(swat.health);
swat.TakeDamage(damage);
}
}
}
Swat_death (player_death) -
using UnityEngine;
using UnityEngine.SceneManagement;
public class swat_death : MonoBehaviour
{
static float health = 250f;
public GameObject player;
public void TakeDamage(float amount)
{
health -= amount;
Debug.Log(health);
if (health <= 0f)
{
Debug.Log("STOP");
SceneManager.LoadScene("death_scene");
}
}
void Die()
{
}
private void OnCollisionEnter(Collision collision)
{
if(collision.transform.tag == "enemy_bullet")
{
//SceneManager.LoadScene("death_scene");
}
}
}
And the PBR_Death (from where the spawning starts) -
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PBR_death : MonoBehaviour
{
public GameObject player;
Animator anim;
public int XPos;
public int ZPos;
public GameObject TheEnemy;
public int enemyCount = 0;
public int points = 1;
public GameObject enemyGameObject;
void Start()
{
anim = GetComponent<Animator>();
enemyGameObject = GameObject.FindWithTag("PBR");
}
// Update is called once per frame
void OnCollisionEnter(Collision collision)
{
if (collision.transform.tag == "bullet")
{
anim.SetTrigger("isDying");
enemy_movement enemy = GetComponent<enemy_movement>();
enemy.enabled = false;
PBR_shooting shoot = GetComponent<PBR_shooting>();
shoot.enabled = false;
scoreManager.score += points;
GameObject go = Instantiate(enemyGameObject, new Vector3(Random.Range(34, 0), Random.Range(34, 0), 0), Quaternion.identity) as GameObject;
go.AddComponent<prefab_movement>();
go.AddComponent<prefab_death>();
go.AddComponent<prefab_shooting>();
// StartCoroutine(EnemySpawner());
Destroy(collision.gameObject);
}
}
Pls help me, I am stuck in this for almost 3 days..
You didn't call the function
In your first script (prefab_shooting-) You didn't call the Shoot() function.

Unity-Breakout Game with a Healthbar

I'm making a breakout game, and I wanted to add a healthbar that decreases when the ball touches a certain object with the tag "hazard". I have a Game Manager Script, and A Pickup interact script, but with the way I set it up, I'm kind of confused with how to trigger takedamage from my GM script to my pickup script, considering I put my playerhealth elements into my GM script, so I can attach it to empty gameobject call Game Manager, since the actual player isnt in the hierarchy, but instantiated during runtime. I'm hoping I don't have to redo the whole thing just for this purpose. If someone could help me figure this out, I'd appreciate it.
Here's my GM script:
public class GM : MonoBehaviour
{
public int lives = 3;
public int bricks = 20;
public float resetDelay = 1f;
public Text livesText;
public GameObject gameOver;
private GameObject clonePaddle;
public GameObject youWon;
public GameObject bricksPrefab;
public GameObject paddle;
public GameObject deathParticles;
public static GM instance = null;
public int startingHealth = 100;
public int currentHealth;
public Slider healthSlider;
bool isDead;
bool damaged;
void Awake()
{
currentHealth = startingHealth;
TakeDamage(10);
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
Setup();
}
public void TakeDamage(int amount)
{
damaged = true;
currentHealth -= amount;
healthSlider.value = currentHealth;
if (currentHealth <= 0)
{
LoseLife();
}
}
public void Setup()
{
clonePaddle = Instantiate(paddle, transform.position, Quaternion.identity) as GameObject;
Instantiate(bricksPrefab, transform.position, Quaternion.identity);
}
void CheckGameOver()
{
if (bricks < 1)
{
youWon.SetActive(true);
Time.timeScale = .25f;
Invoke("Reset", resetDelay);
}
if (lives < 1)
{
gameOver.SetActive(true);
Time.timeScale = .25f;
Invoke("Reset", resetDelay);
}
}
void Reset()
{
Time.timeScale = 1f;
Application.LoadLevel(Application.loadedLevel);
}
public void LoseLife()
{
lives--;
livesText.text = "Lives: " + lives;
Instantiate(deathParticles, clonePaddle.transform.position, Quaternion.identity);
Destroy(clonePaddle);
Invoke("SetupPaddle", resetDelay);
CheckGameOver();
}
void SetupPaddle()
{
clonePaddle = Instantiate(paddle, transform.position, Quaternion.identity) as GameObject;
}
public void DestroyBrick()
{
bricks--;
CheckGameOver();
}
}
And here's my Pickup Script:
public class Pickups : MonoBehaviour {
public float PaddleSpeedValue = 0.5f;
private bool isActive = false;
public float thrust=20f;
public Rigidbody rb;
GameObject player;
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Hazard")
{
isActive = true;
Destroy(other.gameObject);
}
}
}
The Pickups class should not have or store a reference to the player at all (although it is not clear from your question if this is a script attached to the player or attached to something else). Your Game Manager class should. Afterall, it is the class that is responsible for managing the game which includes the player. From there, you can use GetComponent<?>() to access any scripts attached to the player GameObject.
Then as the GM contains a public static reference to itself, any other class can get a reference to the player by doing GM.instance.player as needed, even if the player is created and destroyed several times (as the GM should always have a reference to the current one!)
Presumably the clonePaddle field is the player('s GameObject), all you have to do is make it public.

AddForce doesn't work in Unity

I have the following script
public class SpeedUp : MonoBehaviour {
public Rigidbody2D ball;
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "Ball") {
ball.AddForce(Vector2.left * 1000f);
Debug.Log("ABC");
}
}
}
and every time I run my game, the Debug.Log("ABC") prints ABC in the console, but the Rigidbody doesn't move, it stays as it is. Can someone explain me why, because I don't understand why does the console print work and the Rigidbody doesn't move
This is the code for the Ball
public class Ball : MonoBehaviour {
public Rigidbody2D rb;
public Rigidbody2D hook;
public float releaseTime = 0.15f;
private bool isPressed = false;
void Update()
{
if (isPressed)
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (Vector3.Distance(mousePos, hook.position) > 2.5f)
{
rb.position = hook.position + (mousePos - hook.position).normalized * 2.5f;
}
else
{
rb.position = mousePos;
}
}
}
void OnMouseDown()
{
isPressed = true;
rb.isKinematic = true;
}
void OnMouseUp()
{
isPressed = false;
rb.isKinematic = false;
StartCoroutine(Release());
}
IEnumerator Release()
{
yield return new WaitForSeconds(releaseTime);
GetComponent<SpringJoint2D>().enabled = false;
this.enabled = false;
}
}
The Rigidbody doesn't move may be it's need to getComponenrt()
So, add void Start() method in your the script
public class SpeedUp : MonoBehaviour {
public Rigidbody2D ball;
void Start()
{
ball = ball.GetComponent<Rigidbody2D>();
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "Ball") {
ball.AddForce(Vector2.left * 1000f);
Debug.Log("ABC");
}
}
}

prefab does not work same as its origin

public class green : MonoBehaviour
{
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "BLUE")
{
Destroy(other.gameObject);
gm.mylife -= 1;
}
}
}
public class gm : MonoBehaviour
{
public GameObject blue;
static public bool tr = false;
public Text life;
public static int mylife = 0;
void Start()
{
makebox();
}
void makebox()
{
StartCoroutine("timedelay");
}
IEnumerator timedelay()
{
yield return new WaitForSeconds(3f);
Debug.Log("sdfaDF");
GameObject br = Instantiate(blue, new Vector3(-6, -2, 0), Quaternion.identity) as GameObject;
makebox();
}
void Update()
{
life.text = (mylife.ToString());
}
}
I made a blue box which is destroyed when it meets something and has -1 score.
And it is made at (-2,2)position .
Then I made a prefab. But the prefab does not work as its origin. It is JUST created at the same position as its origin.
I want to make my prefab destroy and score -1 also.
How can i fix it ?
PLEASE HELP ME...
You are spawning the object at same position all the time:
GameObject br = Instantiate(blue, new Vector3(-6, -2, 0), Quaternion.identity) as GameObject;
Instead you should give a new position every time like this:
public Vector3 offSet = new Vector3(2,0,0);
Vector3 pos;
IEnumerator timedelay()
{
yield return new WaitForSeconds(3f);
Debug.Log("sdfaDF");
GameObject br = Instantiate(blue, pos, Quaternion.identity) as GameObject;
pos += offSet;
makebox();
}
GameObject blue = Instantiate(bluep);
blue.tag = "BLUE";
I solved by giving tag to the object at the script.

My shooting script does not work after respawning

I have a character who is able to shoot; however, when the character dies and respawns he is unable to shoot and I get the error:
UnassignedReferenceException: The variable BulletTrailPrefab of Weapon has not been assigned.
You probably need to assign the BulletTrailPrefab variable of the Weapon script in the inspector.
UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, Vector3 pos, Quaternion rot) (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/UnityEngineObject.cs:74)
UnityEngine.Object.Instantiate (UnityEngine.Object original, Vector3 position, Quaternion rotation) (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/UnityEngineObject.cs:84)
Weapon.Effect () (at Assets/Weapon.cs:64)
Weapon.Shoot () (at Assets/Weapon.cs:53)
Weapon.Update () (at Assets/Weapon.cs:33)
If someone can help me fixing this it would be greatly appreciated. I have tried lots of stuff however nothing appears to work.
My weapon script
using UnityEngine;
using System.Collections;
public class Weapon : MonoBehaviour {
public float fireRate = 0;
public float Damage = 10;
public LayerMask whatToHit;
public Transform target;
public Transform BulletTrailPrefab;
float timeToSpawnEffect = 0;
public float effectSpawnRate = 10;
float timeToFire = 0;
Transform firePoint;
float nextTimeToSearch = 0;
// Use this for initialization
void Awake () {
firePoint = transform.FindChild ("firePoint");
if (firePoint == null) {
Debug.LogError ("No firePoint? WHAT?!");
}
}
// Update is called once per frame
void Update () {
if (fireRate == 0) {
if (Input.GetButtonDown ("Fire1")) {
Shoot();
}
}
else {
if (Input.GetButton ("Fire1") && Time.time > timeToFire) {
timeToFire = Time.time + 1/fireRate;
Shoot();
}
}
if (target == null) {
FindBulletTrailPrefab ();
return;
}
}
void Shoot () {
Vector2 mousePosition = new Vector2 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
Vector2 firePointPosition = new Vector2 (firePoint.position.x, firePoint.position.y);
RaycastHit2D hit = Physics2D.Raycast (firePointPosition, mousePosition-firePointPosition, 100, whatToHit);
if (Time.time >= timeToSpawnEffect) {
Effect ();
timeToSpawnEffect = Time.time + 1/effectSpawnRate;
}
Debug.DrawLine (firePointPosition, (mousePosition-firePointPosition)*100, Color.cyan);
if (hit.collider != null) {
Debug.DrawLine (firePointPosition, hit.point, Color.red);
Debug.Log ("We hit " + hit.collider.name + " and did " + Damage + " damage.");
}
}
void Effect () {
Instantiate (BulletTrailPrefab, firePoint.position, firePoint.rotation);
}
void FindBulletTrailPrefab () {
if (nextTimeToSearch <= Time.time) {
GameObject searchResult = GameObject.FindGameObjectWithTag ("BulletTrail");
if (searchResult != null)
target = searchResult.transform;
nextTimeToSearch = Time.time + 0.5f;
}
}
}
My gamemaster script
using UnityEngine;
using System.Collections;
public class GameMaster : MonoBehaviour {
public static GameMaster gm;
void Start () {
if (gm == null) {
gm = GameObject.FindGameObjectWithTag ("GM").GetComponent<GameMaster>();
}
}
public Transform playerPrefab;
public Transform spawnPoint;
public int spawnDelay = 2;
public IEnumerator RespawnPlayer () {
Debug.Log ("TODO: Add waiting for spawn sound");
yield return new WaitForSeconds (spawnDelay);
Instantiate (playerPrefab, spawnPoint.position, spawnPoint.rotation);
Debug.Log ("TODO: Add Spawn Particles");
}
public static void KillPlayer (Player player) {
Destroy (player.gameObject);
gm.StartCoroutine (gm.RespawnPlayer());
}
}
My player script
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
[System.Serializable]
public class PlayerStats {
public int Health = 100;
}
public PlayerStats playerStats = new PlayerStats();
public int fallBoundary = -20;
void Update () {
if (transform.position.y <= fallBoundary)
DamagePlayer (9999999);
}
public void DamagePlayer (int damage) {
playerStats.Health -= damage;
if (playerStats.Health <= 0) {
GameMaster.KillPlayer(this);
}
}
}
Late answer for answering's sake! (Lovely!)
The reason it only happens after you respawn is because when you instantiate a new playerPrefab, the Weapon object (which presumably is part of your player prefab) does not have the assignments you had made in the editor—those assignments are only for the specific instances that were in the editor. You'll need to manually assign it at runtime in one of two ways:
1) When you respawn:
public IEnumerator RespawnPlayer () {
// ...
GameObject playerInstance = Instantiate (
playerPrefab,
spawnPoint.position,
spawnPoint.rotation) as GameObject;
Weapon weaponInstance = playerInstance.GetComponentInChildren<Weapon>;
weaponInstance.BulletTrailPrefab = /* prefab reference */;
// ...
}
2) In your Weapon script:
void Start () {
BulletTrailPrefab = /* prefab reference */;
}
But in either case you would have to have some way of referencing the prefab at runtime, such as putting a reference into the GameMaster script or using Resources.Load().
The error is quite clear. You have not assigned a prefab to your variable..
UnassignedReferenceException: The variable BulletTrailPrefab of Weapon
has not been assigned.
You probably need to assign the BulletTrailPrefab variable of the
Weapon script in the inspector.

Categories