I'm trying to make a brick breaker game in Unity, using 2D. I have an object that randomly spawns when a brick is destroyed. One of them is a "slowdown" object to slow down the projectile. However, whenever I "catch" the spawn with my paddle, it seems as if I don't have the same instance of the ball.
For instance, I Debug.Log the velocity of the ball through RandomSpawns.csscript, it will show as (0,0). At the same time, if I show the ball velocity through ball.cs, it will show the right velocity
RandomSpawning.cs:
using UnityEngine;
using System.Collections;
public class RandomSpawns : MonoBehaviour
{
public paddle paddle;
public LoseCollider loseCollider;
public ball ball;
public Brick brick;
public string nameOfSpawn;
void Update()
{
// Finds object with Spawn tag and if lower than paddle y pos, means
// that player missed the spawn -->destroy to not reset the game
if (GameObject.FindGameObjectsWithTag("Spawn") != null)
{
if (this.transform.position.y < paddle.transform.position.y)
{
Destroy(gameObject);
}
}
}
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "paddle")
{
triggeredEffect();
Debug.Log("Right here");
Destroy(this.gameObject);
}
}
void triggeredEffect()
{
if (string.Equals(nameOfSpawn, "slowdown"))
{
Debug.Log("current velocity " + ball.GetComponent<Rigidbody2D>().velocity);
Vector2 velocity = ball.GetComponent<Rigidbody2D>().velocity;
ball.GetComponent<Rigidbody2D>().velocity = velocity * 0.5f;
Debug.Log("slowdown: new velocity" + ball.GetComponent<Rigidbody2D>().velocity);
}
}
I also tried using this, to no avail:
GameObject ball = GameObject.Find("ball");
ball currentBall = ball.GetComponent<ball>();
Debug.Log("current velocity " + currentBall.GetComponent<Rigidbody2D>().velocity);
Vector2 velocity = currentBall.GetComponent<Rigidbody2D>().velocity;
currentBall.GetComponent<Rigidbody2D>().velocity = velocity * 0.5f;
Debug.Log("slowdown: new velocity" + currentBall.GetComponent<Rigidbody2D>().velocity);
This just gives me an "Object reference not set to instance of object" error.
ball.cs:
using UnityEngine;
using System.Collections;
public class ball : MonoBehaviour
{
private paddle paddle;
private bool hasStarted = false;
private Vector3 paddleToBall;
void Start ()
{
paddle = GameObject.FindObjectOfType<paddle>();
paddleToBall = this.transform.position - paddle.transform.position;
print(paddleToBall);
}
// Update is called once per frame
void Update ()
{
if (!hasStarted)
{
this.transform.position = paddle.transform.position + paddleToBall;
if (Input.GetMouseButtonDown(0))
{
this.GetComponent<Rigidbody2D>().velocity = new Vector2(.5f, 10f);
hasStarted = true;
}
}
}
void OnCollisionEnter2D(Collision2D collision)
{
Vector2 tweak = new Vector2(Random.Range(0f, .2f),Random.Range(0f, .2f));
if (hasStarted)
{
GetComponent<AudioSource>().Play();
GetComponent<Rigidbody2D>().velocity += tweak;
}
}
}