简体   繁体   English

使用C#在Unity中调用不实例化的非静态方法

[英]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: 我正在使用Unity,并使用了一个官方教程,其中包含采用如下形式的C#代码:

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? 我的问题是,FixedUpdate()方法如何直接调用Flip()方法? I thought only static methods can be used without instantiation but obviously Flip() is not a static method. 我以为只能使用静态方法而无需实例化,但是显然Flip()不是静态方法。

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? 是在Vector2()方法上调用了'new'关键字,而Vector2()正是在哪里实例化的呢?

how is the FixedUpdate() method able to call the Flip() method directly? FixedUpdate()方法如何直接调用Flip()方法?

Because FixedUpdate is an instance method, available only when the object is created. 因为FixedUpdate是实例方法,所以仅在创建对象时可用。 At which point, Flip is also available, since it is also an instance method. 此时, Flip也可用,因为它也是一个实例方法。 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: 就是说..如果FixedUpdatestatic ..那将行不通:

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 . 为了使该工作有效,您必须从static方法中实例化对象的新实例,然后调用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. 但是,这样一来,您将无法在方法之间双向共享任何公共状态-实例方法可以访问static状态,反之亦然。

where exactly is Vector2() being instantiated 实例化Vector2()的确切位置

It is instantiated before the call to AddForce and passed in. This is just syntactic sugar and happens transparently. 它在调用AddForce之前实例化并传入。这只是语法糖,并且透明地发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM