I’m a little confused as to why did we use () for the AddTorque but we used = for the boost?
Hi,
That’s a very good question. Thanks for asking.
The object referenced by surfaceEffector2D
has got a property named speed
. For simplicity, let’s say that the property is a variable. At least, it behaves like one, and this means that we are able to assign a value to it.
Here is another example how to assign a value to a variable:
string name = "Rick";
int number = 99;
AddTorque is a method of the Rigidbody2D object. We reference such an object with rb2d
. (If rb2d
does not reference any Rigidbody2D object, you would get a NullreferenceException error. null
means ‘no object reference’.)
In C#, we are able to define methods with parameters. When we call such methods, we must pass on an argument. In this case here, we did not define the method ourselves. Some Unity programmer did.
Here is the method signature from the Unity API:
As you can see, the first parameter is a float, hence we have to pass on a float when we call that method. The second parameter is optional because there is a default value defined with = ForceMode2D.Force
.
A little exercise if you want: Try to find the speed
property of the SurfaceEffector2D class in the Unity API.
When writing code, we usually have to look things up in the Unity API if we don’t know them. Neither speed
nor AddTorque
are natural laws. Somebody wrote the code. We use it. Just like you, we did not know this code when we started with Unity. We looked it up.
Did this clear it up for you?
See also:
- Forum User Guides : How to apply code formatting within your post
- Forum User Guides : How to mark a topic as solved
This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.