[Unity3d] Gameobject and Monobehaviour

Source: Internet
Author: User
Tags tag name

the Game object (Gameobject) is a container for all other components (Component). All objects in the game are essentially game objects (Gameobject).

ref:http://blog.csdn.net/linuxheik/article/details/37956243

Create a Game object (Gameobject)

The game object (Gameobject) itself does not add any features to the game. Instead, a container that accommodates the components (Component) that implement the actual functionality.

For example, light is a component (Component) attached to a game object (Gameobject).

Components attached to the game object (gameobject) (Component)

# Note the sequencing

If you want to create a component from a script (Component), you should

  1. Create an empty Game object (Gameobject),
  2. Then use the gameobject.addcomponent (ClassName) function to add the required components (Component).   

In scripts, components (Component) can easily communicate with each other through message sending or getcomponent (TypeName) functions. This allows you to write reusable small scripts that can be attached to multiple game objects (Gameobject) and reused for different purposes .

In addition to the container as a component (Component), the game object (Gameobject) has a tag (tag), layer, and name.

    • tag is used to quickly find objects by tag name.
    • layer can be used to cast light, render, or apply lighting to only certain groups of objects.
    • name .

tags and layers (layer) can be set using the Tag Manager (Tag Manager) (in the project Settings, tags), in the editing (edit) settings.

instance ( gameobject and getcomponent) --Object- -Routines: Get the object, top-level structure, and then follow its original face getcomponent out.
// Get button Game Object Gameobject. Find ("canvas/button");
// Get button Script Component Button btn = (button) btnobj. getcomponent<Button> ();

-- Monobehaviour- -
using Unityengine; using Unityengine.ui;
  
 Public class  monobehaviour {    publicvoid  Button_Click ()    {        ...    }}

the relationship between Monobehaviour and Gameobject

Ref:unity script base class Monobehaviour relationship to Gameobject

First, Monobehaviour life cycle

1.1. Built-in function list

Awake: When a script is instantiated, awake is called. Most of us do the initialization of member variables in this class. Start: Called only before the Update function is called for the first time. Because it is called after awake, we can initialize some variables that need to depend on awake in start. At the same time, most of us execute startcoroutine in this class to perform some process triggering. Note that when you write a script in C #, you must start a co-process using Startcoroutine, but you do not need to do this if you are using JavaScript. Update: When the game frame starts playing (at this point, Gameobject has been instantiated), its update is called at each frame. Lateupdate:lateupdate is called after all the Update function calls. Fixedupdate: When Monobehaviour is enabled, its fixedupdate is called at each fixed frame. Onenable: This function is called when the object becomes active or active. Ondisable: This function is called when the object becomes unavailable or inactive. OnDestroy: This function is called when Monobehaviour will be destroyed.
View Code

See figure: life cycle

Next, make an explanation:

The first method to execute is awake, which is the beginning of the life cycle, the initialization code for activation.

In general, you can disable the current script in this place: This.enable=false, if you do this, you will jump directly to the Ondisable method to execute once, and then any other methods will no longer be executed.

If the current script is in a usable state, the normal execution order is to continue to execute onenabledown.

Of course we can implement this script component's startup in another script: this.enable=true;

If the start method is not executed, it will be executed once and if it has been executed, it will not be executed again.

What does that mean? We can disable This.enable=false in a script, and then turn it on to onenable, then proceed down to find that start has been executed and will no longer be executed.

For example: When first enabled, the initial position of the monster is set at the (0,0,0) point, then the monster may have a position change, and then disabled, again enabled, will not let the monster back to the original (0,0,0) position.

Continue backwards, that is, update , then fixupdate, then lateupdate, if Resetis written back, it will go back to update, The 4 events can be circulated in a circular flow .

And then go back to the render module (Rendering), and one of the most important ways is Ongui, which is used to draw the graphical interface. "Of course, if you use NGUI, you don't have to think about this life cycle."

First we talk about the difference between GUI and Ngui,

GUI is Unity's own drawing interface tool, its imaging principle is based on the surface, so the execution efficiency is very low, and does not provide the interface of complex UI, even if developers bite the bullet to write can only make the UI execution less efficient.

NGUI is completely dependent on the 3D as if the camera in the world of the game is directly shining in a plane, drawing its own UI on top of the plane, so it will perform very efficiently.

Ngui is a charge plug-in, in the asset store you can see the price. There are two ways we can use Ngui without a genuine purchase,

    • The first: The use of the official free version, but this version of the Ngui watermark, can not be formally released but it is fully available as a learning.
    • The second kind: Use the genuine plug-in purchased by others, in the Internet has friends release Ngui plugin.

Then backwards, is the unloading module (TearDown), here there are two methods ondisable and OnDestroy. When disabled (Enable=false), the Ondisable method is executed, but at this time the script is not destroyed, and in this state it can be returned to the Onenable State (enable=true).

When manually destroyed or the attached game object is destroyed, OnDestroy is executed and the current script's life cycle ends.

It is particularly emphasized that although C # can be used to write code here, the life cycle of this class constructed object is completely different from the life cycle of the monobehaviour.

Ii. Those pits of the monobehaviour
    • Private and protected (protected) variables can only be displayed in expert mode. The property is not serialized or displayed in the Inspector panel.
    • Do not use namespaces (namespace)
    • Remember to use the cache component Lookup , the component that is often accessed in the long-term approach of monobehaviour, preferably storing it as a private member variable .
    • In the game there is often a need to detect the enemy and our distance between the problem, if you want to find all the enemy, obviously to consume too much of the computation,
      • So the best way to do this is to use collider for the attack range, and then set the collider Istrigger to True.
      • Finally, the ontriggerenter is used for distance detection within the attack range , which can greatly improve program performance.

Iii. Common methods of Monobehaviour
Update when the Monobehaviour instantiation is complete, update is called at each frame. Lateupdatelateupdate is called after all the Update function calls. This can be used to adjust the script execution order. For example: When an object moves in the update, the camera following the object can be implemented in the lateupdate. Fixedupdate processing rigidbody, you need to use fixedupdate instead of update. For example: When you add a force to a rigid body, you must apply a fixed frame in the fixedupdate instead of the frame in the update. (both frame lengths differ) Awakeawake is used to initialize a variable or game state before the game starts. It is called only once throughout the lifetime of the script. Awake is called after all objects have been initialized, so you can safely talk to other objects or search for them with functions such as Gameobject.findwithtag. The Awke on each game object are called in random order. Therefore, you should use awake to set up a reference between scripts and use start to pass information awake is always called before start. It cannot be used to execute a synergistic program. C # and Boo User note: Awake differs from constructors in that objects are constructed without defining the serialization state of the component. Awake is called only once, like a constructor. StartStart is called only once in the life cycle of the behaviour. Unlike awake, Start is called only when the script instance is enabled. You can adjust the deferred initialization code as needed. Awake is always executed before start. Onmouseenter/onmouseover/onmouseexit/onmousedown/onmouseup/onmousedrag when mouse enters/hovers/moves out/clicks/releases/drags Guielement (GU I element) or collider (collision body), call Onmouseenter. Ontriggerenter/ontriggerexit/ontriggerstay Call Ontriggerenter when Collider (collision body) enters/exits/stays on trigger (trigger). Ontriggerstay will be called at each frame. Oncollisionenter/oncollisionexit/oncollisionstay when this collider/rigidbody is called when another rigidbody/collider is triggered. Oncollisionstay will be called at each frame.
Overridable Functions
invokefunction Invoke (methodName:string, Time:float) :voidafter time seconds, the MethodName method is called; Invokerepeatingfunction invokerepeating (methodName:string, Time:float, Repeatrate:float) :voidIt is called once every repeatrate time from the first call. Cancelinvokefunction Cancelinvoke ():voidcancels all calls to invoke on this monobehaviour. Isinvokingfunction isinvoking (methodName:string) :BOOLwhether a specified function is waiting to be called. Startcoroutinefunction Startcoroutine (routine:ienumerator): Coroutine A synergistic program can be used at any location during executionyieldStatement.yieldThe return value controls when the recovery of the cooperative program is performed downward. The Synergy program is excellent during the execution of the object's own frame. The synergistic program has no more overhead in performance. The Startcoroutine function is returned immediately, but yield can delay the result. Until the execution of the collaboration program is complete. Stopcoroutine/Stopallcoroutines
non-overridable functions

Iv. The relationship between scripts and Gameobject

* Instantiation

Gameobject that are explicitly added to Hierarchy are instantiated first, and Gameobject are instantiated from bottom to top.

Gameobject is instantiated at the same time, loading its components component and instantiating,

If the script component is mounted, when the script component is instantiated, the script's Awake method is invoked, and the component's instantiation order is also from bottom to top.

The game does not start playing frames until all explicit gameobject and their components are instantiated.

* After instantiation

when the Gameobject instantiation work is complete, the game frame will start playing . The first frame of each script is called the Start method , each subsequent frame calls Update, and the order in which each script is called from bottom to top in each frame.

* Summary

The script that is mounted to Gameobject is instantiated as a member of the Gameobject .

* The relationship between script and Gameobject

See link content

The drag-and-drop binding method in the Nb:unity editor is gameobject level.

[Unity3d] Gameobject and Monobehaviour

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.