Common API( a key )

Ø  introduce : Application programming interface , Are some predefined functions

Unity The engine provides rich components and class libraries , Great convenience for developers , Soviet Union from , Master and use these API It is very important to improve the efficiency of game development

Ø  be careful :

1. No component now, If you need to add components to an object , Calling the object's AddComponent method

2. All classes attached to objects , Must inherit from Component

Component

Ø  Common properties :gameObject  transform colliderrenderer

Ø  common method : GetComponentGetComponentInChildren GetComponentInparent

Ø  Small exercises :

  method     ( The method is called by the game object , Not a class )

       private void Start()

       {           //this Represents the game object

           // Attach to 2 Of objects , ask : What object's position is obtained ?

             Vector3 pos = this.transform.position;

           Debug.Lod(pos);//? First get the 1 Location of objects , Get the 2 Location of objects

        }

       private void OnGUI()

        {

           if(GUILayout.Button("GetComponent"))// Runtime in Unity Generate a button , Click Run 1 Next lower code

           {  //GetComponent : Find components by type in the current object

               // Modify the current object color      Script object --> Component object --> attribute

          this.GetComponent<MeshRenderer>().material.color = color.red

               // conclusion : obtain 1 Component references , To get other types of component references

           }

            if(GUILayout.Button("GetComponent"))

           {                // Find all components in the current object

               Var all Component = this.GetComponents<Component>();

               foreach(var item in allComponent)

               {

                    Debug.Lod(item);

               }

               var allScript =
this.GetComponents<MonoBehaviour>();// Find all scripts . Scripts inherit from MonoBehaviour class , Find your son and write about your father

               foreach(var item in allScript)

               {

                    Debug.Lod(item);

               }

           }

        if(GUILayout.Button("GetComponent"))

          {  // Find from yourself All descendant objects specify type components

           var renderer = GetComponentInChildern<MeshRenderer>();

           // Find from yourself All predecessor objects specify type components

           var renderer = GetComponentInParent<MeshRenderer>();

           }

        }

Transform

Ø  sketch : Provide setting position and orientation +/( stay , move , autobiography , Rotate around , Annotation rotation )

lookup ( By name , Index sub object , father , Root object ) function .

Ø  Transform Member variable of component

Ø  Transform Member functions of components

Ø  Application example :

1.   Move forward

2.   Around its own axis y Axis rotation

3.   Around the world axis y Axis rotation

4.   Make the viewing direction of the camera follow the object

Ø  Classroom exercises :

public classTransformDemo02 : MonoBehaviour

{

    public Transform target;

    public string childName;

    private void OnGUI()

    {

        #region position , Azimuth correlation

        // Coordinates relative to the world coordinate system

        Vector3 worldPos = transform.position;

        // Coordinates relative to the parent [ Show in compiler ]

        Vector3 localPos =transform.localPosition;

        // Scale relative to parent [ Show in compiler ]

        Vector3 localScale =transform.localScale;

        // Understood as : Scale relative to model ( Parent object .localScale * Current object .localScale)

        Vector3 lossyScale =transform.lossyScale;

        if (GUILayout.Button(" Move forward 1m( oneself )"))

        {

            // Move along its own coordinate system

            transform.Translate(0, 0,1);//translate: transfer

        }

        if (GUILayout.Button(" Move forward 1m( world )"))// Once per frame

        {

            // Move along the world coordinate system

            transform.Translate(0, 0, 1,Space.World);

        }

        if (GUILayout.RepeatButton(" along y Axis rotation 1 degree ( oneself )"))

        {

            // Rotate along its own coordinate system

            transform.Rotate(0, 1, 0);

        }

        if (GUILayout.RepeatButton(" along y Axis rotation 1 degree ( world )"))

        {

            // Rotate along world coordinate system

            transform.Rotate(0, 1, 0,Space.World);

        }

        if(GUILayout.RepeatButton("LookAt"))

        {

            // Fixation rotation (z Axis points to target object position )

            transform.LookAt(target);

        }

        if(GUILayout.RepeatButton("RotateAround"))

        {

            // Rotate around ( Points around , Axis around , Rotation angle )

           transform.RotateAround(target.position, Vector3.right, 1);

        }

        #endregion

 

        #region lookup

        if (GUILayout.Button(" Find sub objects by name "))

        {

            // demand : Get the MeshRenderer assembly

            // name --> Transform component --> Other components

            Transform tf =transform.Find(childName);  // Only children can be found

           tf.GetComponent<MeshRenderer>().material.color = Color.red;

            // shortcoming : Restricted object hierarchy

            // proposal : Searching a descendant object recursively by method

            //transform.Find(" Subobject / Subobject ")

        }

        if (GUILayout.Button(" Find sub objects by index "))// Find by index , Index order and Unity Panel order is consistent

        {

            //transform.childCount Number of sub objects

            // demand : Get all sub objects ( first generation )

            for (int i = 0; i <transform.childCount; i++)

            {

                Transform childTF = transform.GetChild(i);

            }

        }

        // Get parent

        Transform parentTF =transform.parent;

        // Set parent

        //transform.SetParent( Parent transformation component );

        // Get root object     Root object : The object at the top of the hierarchy

        Transform root = transform.root;

        #endregion

    }

}

 

GameObject

sketch : Provides operation on objects ( establish , activation , Disable , lookup ( label )) function

be careful : Lower case is object reference (gameobject) Capitalized is the class name (GameObject)

Small exercises :

   public class GameObjectDemo03 : MonoBehaviour

{

    // variable :

    //activeInHierarchy Active state of the object in the scene

    //activeSelf  Active state of the object itself

    // If the parent object is disabled , Sub objects are also disabled in the scene .

    // here , Subobject activeInHierarchy by false,activeSelf by true.

    public GameObject targetGO;

    private void OnGUI()

    {

        // demand : Disable / Enable object

        if (GUILayout.Button(" Disable / Enable object "))

        {

           targetGO.SetActive(!targetGO.activeInHierarchy);

        }

        // demand : Create a red spotlight

        if (GUILayout.Button(" Create a red spotlight "))

        {

            GameObject go = newGameObject("MyLight");

            Light light =go.AddComponent<Light>();

            light.color = Color.red;

            light.type = LightType.Spot;

        }

        if (GUILayout.Button(" Create a red spotlight "))

        {

            // Too many objects in the scene , therefore Use with caution   .

            //GameObject go01 =GameObject.Find(" Object name ");

          

            // Find a single object by label

            GameObject playerGO = GameObject.FindWithTag("Player") <>;

            // Find all objects using the specified label

            GameObject[] allEnemy =GameObject.FindGameObjectsWithTag("Enemy");

        }

    }

Object class ( Provided function )

sketch :Unity All the things that can be used in China are called object

 

induce 4 Common classes , Search method

 Component class : Find components ( Parent object , Root object , By name , Index sub object )

    GetComponent: Find components by type in the current object  

       this.GetComponent<MeshRenderer>().material.color= Color.red;

    GetComponents: Find all components in the current object

        varallComponent = this.GetComponents<Component>();

    GetComponentChildern: Find all descendant objects from itself and specify type components

        var rendererChildern =this.GetComponentChildern<MeshRenderer>();

    GetComponentParent: Find all ancestor specified type components from itself

   varrendererParent = this.GetComponentParent<MeshRenderer>();

Transform class : Find transform components ( Parent object , Root object , By name , Index sub object )

Find objects by name :

   transform.Find(" Subobject / Subobject ")

          Transform tf = transform.Find(childName);// Only children can be found

Find sub objects by index :

   Transform childTF02 = transform.GetChild(0); // According to index

Transform[] childTF = newTransform[transform.childCount];  // Get all      

    for(inti=0;i<transform.childCount;i++)

    {

       childTF = transform.GetChild(i);

    }

    Find parent

    Transform parentTF = transform.parent;

    Find root object

    Transform root = transform.root;

GameObject class : Through Tags , Name find game object , GetComponent Find components ( Current object , Forefathers , Offspring )

     Find a single object by label :

    GameObject playerGo = GameObject.FindWithTag("player");

    Find all objects using the specified label :

    GameObject[] allEnemy = GameObject.FindGameObjectsWithTag("Enemy");

object class :  Find objects ( assembly object ) According to type

     // Gets all objects of the specified type

            //FindObjectsOfType<Enemy>()

            FindObjectsOfType<Enemy>();

      // Gets an object of the specified type

            //FindObjectOfType<Player>()

 

Time

sketch :ity Through Time Class to get information about time , Can be used to calculate frame rate , Adjust time passing speed and other functions

Constant speed : If you are moving in a rendered frame , Must be multiplied by the interval per frame in speed , To get a constant speed

for example : transform.Rotate(0,Time.deltaTime*speed,0)

Time scaling ( Overall game progress ):

essence : influence fixedUpdete Execution frequency

conclusion : No impact Update Execution frequency ( Does not affect rendering ) influence Time.deltaTime

Game paused for 0 The game continues for 1 Fast forward to 2 Game slow motion 0.5

Time.TimeScale= value ?

 

 

Time Member variable of class :

Prefabricated parts Prefab ( Countdown exercise )

Ø  A resource type , You can instance multiple times in the scene

Ø  advantage : Changes to the preset , Can synchronize to all instances , So as to improve development efficiency

Ø  If you modify the property value of an instance separately , The modified value does not change with the prefabricated parts

Ø  Select key : Select the corresponding prefabrication through the prefabrication instance

Ø  Revert key : Discard instance property value , Restore prefab property values

Ø  Apply key : Apply changes from one instance to all instances

Ø  demand : use Text Fabrication of countdown prefabrication , from 02:00 start , last 10 Seconds in red , At 00:00 Stop timing after

 //********************** Scheme I ******************************

// a key :① Define next modification time ② When arrival time ③ Executive logic ④ Add one second to the current time

// Grammatical focus :  Time.time( The current real time when the game starts )

//            string.Format(" placeholder ", variable )( stay Unity Placeholders used in )

private Text textTimer;

     publicint num = 120;

     voidStart()

     {

        textTimer = GetComponent<Text>();

     }

     voidUpdate()

     {

        Timer();

     }

    private float nextTimer = 1;

     void Timer()

     {

         if(nextTimer <= Time.time)

         {

            num--;

            textTimer.text = string.Format ("{0:d2},{1:d2}", num / 60, num%
60);

            nextTimer = Time.time + 1;

         }

         if(num <= 10)

         {

            textTimer.color = Color.red;

         }

     }

//********************** Scheme II ******************************

// a key :① Define the variables used to record the accumulated time ② Accumulate every frame interval ③ When it's time ④ Executive logic ⑤ The variable for clearing the accumulated time of the record

// Grammatical focus :   Time.deltaTime( All the time of the previous frame , That is, every frame interval ) 

private int num = 120;

private Text textTimer;

private float newTimer;

public float intervalTimer=1;

void Start()

{

   textTimer = GetComponent<Text>();

}

 

void Update()

{

   Timer();

}

 

void Timer()

{

   newTimer += Time.deltaTime;

    if(newTimer >= intervalTimer)

    {

       num--;

       textTimer.text=string.Format("{0:d2}:{1:d2}", num / 60, num %60);

       newTimer = 0;

    }

}  

//********************** Scheme 3 ******************************

// Grammatical focus : 【 Repeat call 】   InvokeRepeating(“ Method name ”, Start execution time , interval )

//           【 Delay call 】   Invoke(" Method name ", Start execution time )

//           【 Cancel call 】   CancelInvoke(“ Method name ”) 

privateText textTimer;

privatefloat num = 120;

publicfloat intervalTimer=1;

publicfloat startTimer = 1;

voidStart()

{

 textTimer =GetComponent<Text>();

 InvokeRepeating("Timer", 1, 1);

}

 

void Timer()

{

    num--;

    textTimer.text =string.Format("{0}:{1}", num / 60, num % 60);

    if (num == 0)

    {

        CancelInvoke("Timer");

    }

}

Random class

sketch : Can be used to generate random numbers , Random point or rotation

Random Member variable of class :

Mathf class

sketch : Provides common mathematical operations

Mathf Class

Mathf Common methods of class

Coroutine Synergetic program

sketch :
Also known as the same procedure or cooperation , Cooperative program can run in parallel with main program , It's similar to multithreading, but at any given time, only one coroutine is running , Other programs hang . Cooperative programs can be used to achieve the effect of letting a program wait for a period of time to continue running .

for example : Execution steps 1 , wait for 3 second ; Execution steps 2, Wait for a condition to be true; Execution doesn't go ...

Unity The functions related to the coroutine are :

be careful : stay c# in , Return type of collaboration function must be IEnumerator,yield To use yieldreturn To replace , And start the collaboration program right StartCoroutine function

routine :

The test result is :

Technology
©2019-2020 Toolsou All rights reserved,
QCustomPlot series (5)- Real time dynamic curve python To solve the problem of dictionary writing list in GDOI2019 travels Java Basics ( Bubble sort )Unity Scene loading asynchronously ( Implementation of loading interface )" Cephalosporin wine Say go and go "? DANGER ! Don't drink alcohol when taking these drugs 2021 year 1 Monthly programmer salary statistics , average 14915 element Huawei certification HCIA-AI artificial intelligence java Simple lottery algorithm , luck draw DemoNOI2019 travels