Recently I started learning C# and decided to check out some tutorials and I checked out some tutorials (big surprise!). Anyways it was one by Gucio Devs however I understood all of it except for one part. The whole code is like this:
using UnityEngine;
using System.Collections;
public class player : MonoBehaviour {
public float speed = 50f;
public float jumpPower = 150f;
public bool grounded;
private Rigidbody2D rb2d;
void Start ()
{
rb2d = gameObject.GetComponent<Rigidbody2D> ();
}
void Update ()
{
}
void FixedUpdate()
{
float h = Input.GetAxis('Horizontal');
rb2d.AddForce((Vector2.right * speed) * h);
}
}
the part I am confused in is:
private Rigidbody2D rb2d;
I have also encountered this in Brackeys tutorial the basic syntax type he used was:
Private (another script name) (variable name);
The private access modifier will make the field in this case private to the class called player. If it was public you would see it in your inspector and other objects that have a reference to an instance of the player class would be able to set/get that field. Its a way of protecting it in some sense or at the very least trying to keep things nice and clean and less busy. Sometimes this is due to the design of the classes, other times for other mentioned reasons. You can see that rb2d is set in the Start method and used internally to that class based off what you have posted. There isn’t a reason to expose it, unless you have a need to modify it through another object(s). Think of it as containment by design.
That’s just basic C#, really:
-
private means this variable can only be accessed by this class. You can’t access it from outside an instance of this class;
-
RigidBody2D is the type of the variable. In case you haven’t noticed, Unity creates a script file with a class declaration with the same name of the script(as such: public class ScriptName). Then you can refer to instances of this class by declaring a variable with its name. RigidBody2D is one of Unity’s many built-in classes;
- and rb2d is the variable name, but that you know already.
If your problem is about what RigidBody2D is, I suggest you study Unity’s scripting reference, and also basic C# object oriented programming.