What does "public Paddle paddle" do exactly?

With this line of code that is written in the script attached to the ball:
“public class Ball : MonoBehaviour {
public Paddle paddle;”

What does “public Paddle paddle” do exactly? Does it create an instance of the class Paddle named paddle? Do i access the gameobject paddle or the script that is attached to the paddle? Having done that, why do i need to drag the paddle from the hierarcy in UNITY? what happens when i do that?

I feel quite confused how gameobjects and scripts hang together and how you can access different scripts and gameobjects. Maybe it is being taught later in the course? I really feel like i want to learn this “structure” so i can understand what I am doing.

By public Paddle paddle; you are giving the name paddle to a variable of type Paddle (which is a component within the project) and saying that you are going to address it’s value by outside factors (when you say that it is public), which is the inspector in this case. Initializating this variable will allow you to cash the memory of the script that you are accessing inside it so you don’t have to look for it again later in the code that you are writing. And you have to drag the GameObject to the inspector because the engine still don’t know which instance of “Paddle” you are trying to address. You could, for example, set it just as Paddle paddle; without the public and then address the value under the void Start() method with paddle = FindObjectOfType<Paddle>().GetComponent<Paddle>();

Doing this allows you to find public variables and public methods within the Paddle Script by typing paddle.*Variable/Method*

3 Likes

If I were stuck up a creek…

…it would be good to know that there was a public (thus it’s available to me or anyone else) Paddle (the Type of thing I need) that I could use… the locals call it paddle:slight_smile:

2 Likes

Thanks!
Joao_Dalvi: realised i asked a similar question in the text adventure game :slight_smile: its becoming more clear now!

2 Likes

You are welcome LuckieLuuke, I’m glad I could help! Those syntaxes are a little strange at first but once we start understanding the programming logic it becomes easier to interpret them :slight_smile:

1 Like

Privacy & Terms