Snik
Snik

Reputation: 171

Non-static method called without instantiation in Unity using C#

I was working with Unity and used an official tutorial which contained C# code that took the form as seen below:

public class P1_ActionController : MonoBehaviour 
{

  void FixedUpdate() 
  { 
   if (move > 0 && !facingRight) 
    {
     Flip();
    }
  }

  void Flip() 
  {
    //blah blah, something unimportant goes here.
  }

}

My question is, how is the FixedUpdate() method able to call the Flip() method directly? I thought only static methods can be used without instantiation but obviously Flip() is not a static method.

Also, in a related conundrum within the same code block is this line:

        rigidbody2D.AddForce(new Vector2(0,jumpForce));

Being that the 'new' keyword is invoked on the Vector2() method, where exactly is Vector2() being instantiated?

Upvotes: 0

Views: 922

Answers (1)

Simon Whitehead
Simon Whitehead

Reputation: 65069

how is the FixedUpdate() method able to call the Flip() method directly?

Because FixedUpdate is an instance method, available only when the object is created. At which point, Flip is also available, since it is also an instance method. Its called all within the same instance of an object. When you're inside an instance method - you are within the scope of an actual object instance. That means you're able to call other instance methods or access other instance variables.

That said.. if FixedUpdate was static.. then this wouldn't work:

static void FixedUpdate() 
{ 
   if (move > 0 && !facingRight) 
   {
       Flip(); // BOOOM! CRASSSHHH!! Won't work
   }
}

To make that work, you would have to instantiate a new instance of your object from within the static method then invoke Flip. But, then, you wouldn't be able to share any common state both ways between the methods - the instance method could access static state, but not the vice versa.

where exactly is Vector2() being instantiated

It is instantiated before the call to AddForce and passed in. This is just syntactic sugar and happens transparently.

Upvotes: 5

Related Questions