简体   繁体   中英

Confusion regarding the 'new' keyword in C#, Unity

Maybe a silly question, but having difficulty understanding it.

public class A
{
  public void Message()
    {
      Debug.Log("Some Message")
    }
}

public class B: MonoBehaviour
{
  A obj1 = new A(); //instance of object is made and constructor is called
  A obj2;           // object is made
  
  obj1.Message();
  obj2.Message();

 void Start(){}
 void Update(){}
}

What's the purpose of 'new' keyword if in both cases, the object is able to use methods of the class

A obj2;           // object is made

The object is not instantiated at this time, you only told here that you have a variable with the name obj2, and it is hold reference to nothing, in case of class it is null . You have a class named A and in it, you have a method called Message() and compiler in compile-time have a signal you have Message method defined, and that it is. In this case, this code should throw an exception NullReferenceException

There are a few quirks to Unity which may be tripping you up here. Actually, obj2 is not null, because it is of type "A" (not a Monobehavior). Since Class B is derived from Monobehavior, all of its "class variables" (the ones defined in immediate scope) will be instanced by the Inspector automatically. You can read about that here .

In other words, obj2 will still be usable. This is a property of custom classes in regards to how they are loaded from MonoBehaviors. If class A was also a MonoBehavior, then it would be nullable here, and you would see it as an empty variable in your inspector when Class B is put onto a GameObject. This is the case where Message() would not work, since obj2 would actually be null. Note there are other complications though--if Class A is a MonoBehavior, then you shouldn't be using Constructors on it, you should be using AddComponent(). Also, you can't define two MonoBehaviors in the same script file.

Finally, I'm not sure of the specifics here since I haven't tested it, but obj1.Message() may not be able to be called from where you're currently doing it. Typically code is run using the Callback functions provided by the MonoBehavior inheritance, ie Start(), Update(), etc. In order to call obj1.Message() at the start of the game, you need to run it from the Start() method. Let me know if you have any questions and I can clear up anything you find confusing!

EDIT: This is only true if obj2 appears in the inspector--if it is public and the class A is tagged as Serializable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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