Script Rigidbody 2D

Hello guys,
what I don’t understand is why we add Rigidbody 2D to an object from both unity and script? Can’t we just add it from unity? For example, what does the script below do?

‘’’
public class playercontroller2 : MonoBehaviour
{
private Rigidbody2D rb;

void Start()
{
rb = GetComponent();
}
}
‘’’

In script, you have no adding. It is getting a reference to a component for further operation in the script. You can delete it, if you have no operation with RB in the script.

Adding via script looks like that:

Rigidbody2D rb = gameObject.AddComponent(typeof(Rigidbody2D)) as Rigidbody2D;

or

Rigidbody2D rb = gameObject.AddComponent<Rigidbody2D>();

Your script is incorrect. You get a rididbody2D component from the object like this:

rb=GetComponent<Rigidbody2D>();

But if you don’t like doing this then you can make the rigidbody field public and use the editor to drag the rigidbody onto it.

public Rigidbody2D rb; 

here is the correction of your code

public class playercontroller2 : MonoBehaviour
{
private Rigidbody2D rb;

void Start()
{
rb = GetComponent<Rigidbody2D>();
}
}

in general it is easier to learn programming if you think it like an example in real life.

if I tell you to go to this gamestop game you never knew about it you will ask, “where is it?”

so there are these lines in code that deals with “where is this and that”

then there are various ways to keep track of this “where” information, sometimes you need that info just once and then forget about it, so you don’t need to declare that private variable, you can get the rigidbody component in one line of code directly. Or sometimes you need to use that information in multiple places so it make sense to declare it and set it once and then reuse it.

There is also a tradeoff of speed between on “finding on the fly” versus “set stuff at the start of the level” but that is critical when you have a lot of scripts and objects and stuff in your game