Why don't we need new when creating paddleToBallVector

I understand the new keyword is making an object from the Vector2 class when we type in
Vector2 paddlePostion = new Vector2(…);

Why didn’t we need to do this for paddleToBallVector? Don’t we need to make an object called paddleToBallVector?

Hi,

What did we do with the variable? Did we expose it in the Inspector with [SerializeField]? Did we assign an existing Vector3 object to it?

Yes we made it a SerializeField. In start method below we assigned it a value

public class Ball : MonoBehaviour
{ //this is our configuration parameters
[SerializeField] Paddle paddle1;
[SerializeField] float xPush = 2f;
[SerializeField] float yPush = 15f;

Vector2 paddleToBallVector; 
bool hasStarted =false;   
void Start()
{
    paddleToBallVector = transform.position - paddle1.transform.position;
  
}
private void lockBallToPaddle()
{
    Vector2 paddlePosition = new Vector2(paddle1.transform.position.x, paddle1.transform.position.y);
    transform.position = paddleToBallVector + paddlePosition;
}
// ...

}

In that case, Unity creates an object automatically for us when we assign our script to an Inspector. You can change the values in the Inspector.

Thanks. I was really stuck on that. Is the concept of serializing it an OOP principle or Unity only? I wanted to learn more about it.

Hard to tell because we are not writing the entire program with C#, just a part of it. A lot “magic” is going on in Unity behind the scenes. Unity has got its own rules which sometimes contradict OOP principles, and most of it is not open-source.

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

Privacy & Terms