Quick question on different ways to write code

In lecture 97 (Unity 3D) we are to add a Rigidbody component to an enemy object on Start().
I messed about with this a little and came to the solution:

gameObject.AddComponent<Rigidbody>().useGravity = false;

With the idea to stop gravity at the moment the Rigidbody component is added. I tested it and it all seems to work as intended.

In the lecture itself though, the example went as follows:

        Rigidbody rb = AddComponent<Rigidbody>();
        rb.useGravity = false;

If both of these work (or I might be wrong), why use the second example and create more lines of code (he goes on to refactor the code into it’s own method), when it can be done within the same line of code?

The first example uses a concept called method chaining. It works because AddComponent() returns the Rigidbody that was created. The advantage of using this method is that it does everything in a line of code. The disadvantage is that it can be hard to read. Method chaining is very heavily used in Linq expressions (C#'s query like functions)

In the second example, we’re creating a temporary variable (on the stack) to represent the pointer to the RigidBody. This allows us repeated access to the Rigidbody. It’s more commonly used when you would be caching that variable for future use. Things like a global variable where you might access the Rigidbody at a later point in the program. It’s also, however, much easier to read.

To be clear, neither method is “wrong”. Advanced programmers will prefer method chaining, while newer programmers will tend to prefer the more verbose method for it’s readability.

Hi Brian,

Thanks for the clear explanation!

I’m not yet that far into programming to fully know what a Linq expression really is, or how the stack (or heap) really works. Only that they exist :sweat_smile: But at least it’s good to know that it’s not wrong to write it in the manner I did.

I’m sure I will understand better what way of writing such a line of code suits a certain situation when I am further down the line :slight_smile:

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

Privacy & Terms