[SOLVED] Ball scripts fails to play sound OnCollisionEnter2D

Hello,

I am stuck with OnCollisionEnter2D function not working. It just trigers twice on start and stops.

My project files (Unity 5.1.1) mvcexpress.org/temp/learnUnity/myBrakeOut.zip

Hi there,

The problem is that the Ball script gets destroyed when the game starts, and this is the script in which the OnCollisionEnter2D you’re referring to is. You could rewrite your Ball.cs script so that it doesn’t get destroyed, by adding a boolean hasStarted variable to keep track of whether the game has started or not:

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(AudioSource))]
public class Ball : MonoBehaviour {

    private Paddle paddle;
    private Vector3 padletoBallVector;
    private bool hasStarted = false;

    // Use this for initialization
    void Start () {
	    paddle = FindObjectOfType<Paddle>();
        padletoBallVector =  this.transform.position - paddle.transform.position;
        GetComponent<AudioSource>().Play();
    }
	
	// Update is called once per frame
	void Update () {
        if (!hasStarted)
        {
            this.transform.position = paddle.transform.position + padletoBallVector;
            if (Input.GetMouseButtonDown(0))
            {
                this.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 10f);
                hasStarted = true;
            }
        }
    }

    void OnCollisionEnter2D(Collision2D collision) {
        GetComponent<AudioSource>().Play();
    }
}

Oh… I see! Missed that point.
There should be more elegant way to write it… Maybe even attaching second script.

Thank for your help!