So I have read everyone one else who had this issue here and I can’t figure out what is wrong with my script. Everything works when I declare the paddle public and attach it through the inspector, but as soon as I add the FindGameObjectOfType I get an error.
private Paddle paddle;
private Vector3 paddleToBallVector;
private bool hasStarted = false;
// Use this for initialization
void Start ()
{
paddleToBallVector = this.transform.position - paddle.transform.position;
paddle = GameObject.FindObjectOfType<Paddle>();
}
// Update is called once per frame
void Update () {
if (!hasStarted)
{
this.transform.position = paddle.transform.position + paddleToBallVector;
if (Input.GetMouseButtonDown(0))
{
print("Launching Ball");
hasStarted = true;
this.GetComponent<Rigidbody2D>().velocity = new Vector2(2f, 10f);
}
}
}
}
NullReferenceException: Object reference not set to an instance of an object
Ball.Update () (at Assets/Scripts/Ball.cs:23)
is the error I am getting and my ball wont stick to paddle
I see one problem in your Start function: you use paddle
to make you paddleToBallVector before you find the paddle gameObject in the scene. It should be the other way around:
void Start ()
{
paddle = GameObject.FindObjectOfType<Paddle>();
paddleToBallVector = this.transform.position - paddle.transform.position;
}
If that’s not the issue, try printing debug logs to see if the paddle has been found or not:
void Start ()
{
paddle = GameObject.FindObjectOfType<Paddle>();
if (paddle)
{
Debug.Log("Paddle found");
}
else
{
Debug.Log("Paddle not found!");
}
paddleToBallVector = this.transform.position - paddle.transform.position;
}
That was the problem, Thank you for the help!!