Static methods

Hello,
In this video, when calling GetMouseRay(), we didnt have to create an instance of PlayerController because
GetMouseRay() is static. But what was the reason for making GetMouseRay static. How do we decide that?

GetMouseRay() doesn’t depend on anything within the PlayerController class itself. It gets the Mouse Ray from Camera.Main, and the position of the mouse, neither of which are tied to the Controller. Because of this, we can make the method static.

Most code editors will recognize this and suggest the method be static when extracting the method, or simply by supplying “warnings” in the code editor.

1 Like

What is the advantage of making it static?

Accessibility. Like, for example, what we’re doing here…

Instead of this:

PlayerController callingController = data.user.GetComponent<PlayerController>();
Ray ray = callingController.GetMouseRay();

We can simply use

Ray ray = PlayerController.GetMouseRay();

We actually use Static methods a lot in C#/Unity, without really thinking about it. Here are a few examples of static methods used in the RPG series that would be much more work to implement if we had to instantiate an object to use them:

  • GameObject.FindWithTag
  • Physics.Raycast
  • Physics.RaycastAll
  • Physics.SphereCast
  • The entire Mathf library
  • Debug.Log
  • Random.Range
1 Like

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

Privacy & Terms