Table of contents
3. Compile and run the process
1. Check whether the method is executed or not
-
1. Basic knowledge
-
1. Definition
- The instruction code attached to the game object to define the behavior of the game object
- A script is a class, and when you hang it on an object, you create an object
-
2. Requirements
- use namespace
- Script classes attached to game objects must inherit from the MonoBehaciour class
- The file name must match the class name
- Written scripts must be attached to objects to run
-
3. Compile and run the process
- Source Code - (CLS) -> Intermediate Language - (Mono Runtime) -> Machine Code
-
4. Small knowledge points
- Objects are GameObject objects
- Scripts generally write fields and methods
- Do not write attributes (cannot be displayed in the editor)
- Do not write the constructor (cannot access the main thread in the child thread)
- output to the console
- Debug.Log(“ ”)
- If a component needs to be reused
- Can be moved from the hierarchy panel to the project panel to make a prefab
- The bold font of the prefab will not be modified with the modification of the prefab
-
-
2. Script life cycle
-
1. name
- Also called inevitable event, message Message
- If you want to find an inevitable event, you can search for MonoBehaviour (the parent class of the script) in the unity manual
- Execution order search script life cycle view
- Also called inevitable event, message Message
-
2. Small method
- serialized field
- [SerializeField]
- write above the field
- Function: display private variables in the editor
- [SerializeField]
- hidden field
- [HideInInspector]
- Restricted range
- [Range(0,100)]
- limit to 0 to 100
- [Range(0,100)]
- serialized field
-
3. Initial stage
- Awake
- Execution timing: Execute once immediately after creating the game object
- Script disabled also executes
- private void Awake(){}
- Priority over Start
- Two objects hang scripts at the same time, and Awake executes first
- Role: initialization
- instead of the constructor
- Execution timing: Execute once immediately after creating the game object
- Start
- Execution timing: Execute once after the script starts after the game object is created
- private void Start(){}
- Role: initialization
- instead of the constructor
- OnEnable
- Called whenever the script object starts
- private void OnEnable
- Awake
-
4. Physical stage
- FixedUpdate
- Execution time: After the script starts, the fixed time is called
- The default update frequency is 0.02s
- Suitable for physical manipulation of game objects
- object movement, movement, rotation
- Because the time is fixed, it will not be affected by rendering
- The rendering time is not fixed (the amount of rendering per frame is different, and the performance of the machine is different)
- FixedUpdate
-
5. Game logic
- Update
- Execution time: render frame execution
- The execution interval is not fixed
- Applies to: Kitchen Game Logic
- update map
- LateUpdate
- The delayed update is executed after the Update function is called
- Executed only after one frame, at the same time
- apply following logic
- If Update is written, it may be executed first
- The delayed update is executed after the Update function is called
- Update
-
6. Input events
- mouseover
- OnMouseEnter
- Move the mouse to the current Collider
- mouse over
- OnMouseOver
- Called when the mouse passes over the current Collider
- mouse out
- OnMouseExit
- Called when the mouse leaves the current Collider
- mouse down
- OnMouseDown
- Called when the mouse presses the current Collider
- mouse up
- OnMouseUp
- Called when the mouse is lifted by the current Collider
- mouseover
-
7. Scene rendering
- OnBecameVisible when visible
- Called when the Mesh Renderer is visible on any camera
- OnBecameInvisible when invisible
- Called when the Mesh Renderer is not visible on any camera
- OnBecameVisible when visible
-
8. Closing phase
- OnDisable when not available
- This function is called when the object becomes unavailable or the attached game object is inactive
- OnDestroy when destroyed
- This function is called when the script is destroyed or the attached game object is destroyed
- OnApplicationQuit when the program ends
- Called when the application exits
- OnDisable when not available
-
-
3. Debugging
-
1. Check whether the method is executed or not
- Debug.Log("111")
- The console output is the method call
- print() is also available. print is a method of the MonoBehaviour class, which must be inherited as the parent class
- Debug.Log("111")
-
2. Watch the time change
- Write a time variable, and then Time.time can see the time change on the script property
- Write it in Update
- Try not to use Debug.Log, or consume too much memory
- Write a time variable, and then Time.time can see the time change on the script property
-
3. Start debugging
- The script must be hung on the object first
- vs pressing F5
- Then start the unity point
- When you want to debug, press pause
- Go back to vs and add a breakpoint, and go back to unity single frame operation (right side of pause)
- Then go back to VS and press F11
-
-
4. Animation
-
1. Record animation
- Add component Animation
- create physical file
- Add components in Animation
- For example, rotate to add Rotate
- Record and add keyframes, just change the parameters
-
2. Statement
- play animation
- play
- After the previous animation is finished, play the next animation
- PlayQueued
- Is there any animation playing
- IsPlaying
- play backwards
- Change speed to -1
- Animation[" animation name"].speed=-1
- In order to facilitate modification, try to create a public variable at the top to provide the animation name
- And you need to set the animation time to 1
- Add a statement to judge whether it is at the end
- ComponentName.isPlaying==false
- Component name [animation name].time=component name [animation name].length
- Otherwise the animation does not play, from 0 to 0
- Add a statement to judge whether it is at the end
- Change speed to -1
- play animation
-
-
5. Common APIs
-
1. Component component
- The Component class provides the function of finding (current object, descendants, ancestors) components
- this.GetComponet< component name>().Component content;
- Material is the content inside the MeshRenderer component
- Get all components of the current object
- var variable name = this.GetComponents<Component>();
- Add s to get all components
- foreach(var item in variable name){Debug.Log(item.GetType());}
- var variable name = this.GetComponents<Component>();
- Get the specified type components of descendant objects (including yourself)
- GetComponentInChildren<MeshRenderer>();
- Get the specified type components of ancestor objects (including yourself)
- GetComponentInParent<MeshRenderer>();
-
2. Transform
- Transform provides the function of finding (parent-child root) transformation components and manipulating the position, rotation and scaling of objects
- Get the transformation component of the child object (not including itself)
- foreach(Transform Child in transform){}
- neither grandson
- The position of the object relative to the world coordinate system
- this.transform.position
- this.transform.rotation
- The position of the pivot point of the object relative to the parent object
- this.transform.localPosition
- this.transform.localRotation
- Scale relative to parent object
- this.transform.localScale
- Object and model scaling (self scaling * parent object scaling)
- this.transform.lossyScale
- Move 1 meter to the z-axis of its own coordinate system
- this.transform.Translate(0,0,1)
- to rotate
- this.transform.Rotate(0,0,1)
- revolve around
- this.transform.RotateAround(Vector3.zero,Vector3.up,1)
- Rotate 1 degree around the y-axis at world coordinate 0
- The z axis is forward, and the x axis is
- Move 1 meter to the z-axis of the world coordinate system
- this.transform.Translate(0,0,1,Space.Worle)
- to rotate
- this.transform.Rotate(0,0,1,Space.world)
- Get the ancestor transform component
- root object
- this.transform.root
- parent object
- this.transform.parent
- root object
- Set the parent object of the transform
- this.transform.setParent( parent object,false or true);
- Whether the following false or true changes the position relative to the world coordinates, the default is true
- Find the child object of transform
- Get the number of child objects
- int count = this.transform.childCount
- Get child objects by name
- Transform childTF=this.transform.Find(" child object name")
- Get child object by index
- Transform childTF = this.transform.GetChild(i)
- Get the number of child objects
- Find subchildren when hierarchy is unknown
- recursion
- know the number of children
- Transform parent node.childCount
- own components
- this.transform
-
3. GameObject
- activate or not
- is actually activated
- this.gameObject.activeInHierarchy
- Whether the local is activated (read-only), whether the object is disabled in the Insoector
- this.gameObject.activeSelf
- Set object enable/disable
- this.gameObject.SetActive()
- add components
- ObjectName.gameObject.AddComponent<Light>()
- Find objects by name in the scene (deprecated)
- GameObject.Find(" Game Object Name")
- Finding a needle in a haystack costs performance
- Find by label
- Get all objects with this tag
- GameObject[] allEnemy = GameObject.FindGameObjectsWithTag("标签名")
- Get objects with this tag (single)
- GameObject Enemy=GameObject.FindWithTag("标签名")
- Get all objects with this tag
- is actually activated
- activate or not
-
4. Object
- Delete game objects, components or resources
- Destroy
- Find objects by type
- Object.FindObjectOfType<MeshRenderer>()
- find all objects
- Object.FindObjectsOfType<MeshRenderer>()
- Delete game objects, components or resources
-
5. Time
- Elapsed time since now (read only)
- Time.time
- Time interval in seconds to complete the last frame (read only)
- Time.deltaTime
- Ensure movement speed is independent of render time
- Premise: write code in update
- Generally, the speed is multiplied by time to ensure that the rotation speed is not affected by its performance and rendering volume
- 例如this.transform.Rotate(0,speed*Time.deltaTime,0)
- rotation speed * render interval
- Run in FixedUpdate without multiplying the time interval
- this.transform.Rotate(0,speed,0)
- Premise: write code in update
- game paused
- time scaling
- timeScale
- Pause when it is 0
- 1 at the original speed
- no effect on rendering
- unscaledDeltaTime is not affected by this
- DeltaTime is affected by this
- timeScale
- time scaling
- Individual statements are executed once at specified intervals
- Set a variable to represent the next modification time (be more flexible, do it as soon as you come up, and wait until you finish it)
- Time.time will be modified after this time
- Then the variable is time+interval
- Set a variable to represent the accumulated time (be more flexible, just wait when you come up, and do it after waiting)
- Accumulate with Time.deltaTime
- Modify beyond the interval
- then accumulate to zero
- Call the method repeatedly (suitable for fixed time intervals)
- call in start
- InvokeRepeating ( method name, first execution time, execution interval)
- end repeated calls
- CancelInvoke( method name)
- Execute at specified time
- Called in Start
- Invoke (method name, first execution time)
- Set a variable to represent the next modification time (be more flexible, do it as soon as you come up, and wait until you finish it)
- Elapsed time since now (read only)
-