When to use = and when to use ()

I’m a little confused as to why did we use () for the AddTorque but we used = for the boost?

image

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:
image

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. :slight_smile:


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. :face_with_monocle:

Did this clear it up for you?


See also:

2 Likes

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

Privacy & Terms