[Solved] AutoPlay is not working

Here is my code: using UnityEngine;
using System.Collections;

public class Paddle : MonoBehaviour {

public bool autoPlay = false;

private  Ball ball;

void start(){
	ball = GameObject.FindObjectOfType<Ball>();
}

void Update () {
	if (!autoPlay) {
		MoveWithMouse();
	} else {
		AutoPlay();
	}
}
void AutoPlay()
{
	Vector3 paddlePos = new Vector3 (0.5f, this.transform.position.y,0f);
	Vector3 ballPos = ball.transform.position;
	paddlePos.x = Mathf.Clamp(ballPos.x,0.5f,15.5f);
	this.transform.position = paddlePos;
}
void MoveWithMouse()
{
	Vector3 paddlePos = new Vector3 (0.5f, this.transform.position.y,0f);
	float mousePoseInBlocks = Input.mousePosition.x / Screen.width * 16;
	paddlePos.x = Mathf.Clamp(mousePoseInBlocks,0.5f,15.5f);
	this.transform.position = paddlePos;
}

}
when i start auto play paddle is not moving. how to fix?

Hi,

In case you haven’t figured it out yet, the error in your code is a typo in your start function. Due to this, your code wasn’t able to find an instance of the Ball gameobject which caused the position of your paddle to not update according to the position of the ball, hence making it stationary.

You wrote:

As C# is case sensitive and ‘void Start()’ is a pre-defined method which runs once at the beginning every time you play, therefore the ‘s’ in start must be in upper case like ‘S’, so your code would be:

void Start(){
	ball = GameObject.FindObjectOfType<Ball>();
}

This will make your paddle move and get rid of the ‘NullReferenceException: Object reference not set to an instance of an object’ error in case you were getting it on your console.
Hope this helps.

Cheers & Good Luck,
YA

Thx

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms