当前位置:网站首页>Unity knowledge points (common core classes)
Unity knowledge points (common core classes)
2022-04-23 03:22:00 【C # primary advanced】

One :Transform
Transform Components are Unity3D One of the key points , Mainly due to controlling the rotation of objects 、 Move 、 The zoom .
/*
Member variables :
position: In world space coordinates transform The location of .
localPosition: The position of the transformation relative to the parent . If the transformation has no parent , So equivalent Transform.position
eulerAngles: Rotation in the world coordinate system ( Euler Angle ).
localEulerAngles: The transformation rotation angle relative to the parent .
right: Right direction in the world coordinate system .( Red axis of world space coordinate transformation . That is to say x Axis .)
up: Up in the world coordinate system .( The green axis of coordinate transformation in world space . That is to say y Axis .)
forward: The forward direction in the world coordinate system .( The blue axis of coordinate transformation in world space . That is to say z Axis .)
rotation: Rotation in the world coordinate system ( Four yuan number ).
localRotation: The transformation rotation angle relative to the parent .
localScale: Scale relative to parent .
parent: parent object Transform Components .
worldToLocalMatrix: The point of matrix transformation changes from world coordinates to self coordinates ( read-only ).
localToWorldMatrix: The point of matrix transformation changes from its own coordinates to world coordinates ( read-only ).
root: The name of the root object in the object hierarchy Transform Components .
childCount: Number of sub objects .
lossyScale: Global scaling ( read-only ).
/*
transform.position=new Vector3(0,0,3);// Position shifting
transform.rotation=Quaternion.Eular(0,45,0);// Position rotation Y Shaft rotation 45 degree
transform.localScale=new Vector3(2,2,1); // The zoom
// Member method
transform.Translate(0,0,3);// Position shifting =(Vector3.forward*3); =(new Vector3(0,0,3)) Move forward
transform.Rotate(0,45,0);// around Y Shaft rotation 45 degree
Two : vector (Vector3)
A quantity that has both magnitude and direction is called a vector . In space , A vector is represented by a directional line segment . It can be used to describe physical quantities with two attributes of size and direction , For example, the speed at which an object moves 、 The acceleration 、 Camera viewing direction 、 The force on a rigid body is a vector .

3、 ... and :GameObject
GameObject and gameObject The difference between :
GameObject Is the base class of the game object class
gameObject Is the script mounted object
Method :
Find(、FindWithTagO、FindGameObjectsWithTagO etc.
1) Find... By name :
GameObject player = new GameObject("Player");GameObject go=Gameobject.FinPlayer”);
2) adopt tag Tag to get a single GameObject :
GameObject go=GameObject.FindWithTag(Player”);
GameObject go=GameObject.FindGameObjectWithTag '(Player”);
3) Get multiple groups of game objects through the game tag :
GameObject[]go=GameObject.FindGameObjectsWithTag Player"); Component reference function :
GetComponent
Get the components
GetComponents
Get the list of components ( When used for multiple components of the same type )
GetComponentInChildren Get on an object or sub object
Such as :
ScriptName other=GameObject.GetComponent<ScriptName>():/ Add script on object print(other.name);// You can reference the name in the script through the object
Four :Time
Time.time: Indicates the time from the beginning of the game to the present , Will stop calculating as the game pauses .
Time.deltaTime: Represents the time from the previous frame to the current frame , In seconds .
Time.timeScale: Time scaling , The default value is 1, If set <1, Indicates that time slows down , If set >1, Indicates that time is speeding up , Can be used to speed up and slow down games , Very useful .
// Case study 1: use deltaTime Control object movement
public GameObject cube;
float speed = 3f;
void Update ()
{
cube.transform.Translate(Vector3.forward * Time.deltaTime * speed);
}
5、 ... and : Clone game objects
// Clone the GameObject at the preset position
GameObject go1=Instantiate(cube);
// Clone the game object in a fixed position
//Quaternion.identity The GameObject does not rotate :Quaternion(0,0,0,0)
GameObject go2 =Instantiate(cube,new Vector3(0,0,5),Quaternion.identity);
6、 ... and : Destroy game objects
Destroy Destroy the objects in the scene, but the memory still exists , Or not used again for some time , To destroy and free memory , This avoids frequent read and write operations to memory , The system collector will periodically clean up objects that are not referenced in memory , It's likely that there are places where you still refer to the object, where you don't even know , Or where you ignore , Direct destruction will lead to the reference error of empty reference in the reference place .
// For example, if you want to destroy the under an object 10 Sub objects , Suppose you want to destroy A Under an object a0--a9,10 Sub objects
///<summary>
/// The script hangs on A On objects
/// <summary>
public class AGameOnject: MonoBehaviour
{
void Start ()
{
for (int i = 0; i < transform.childCount; i++)
{
Destroy (transform.GetChild (i).gameObject);
}
}
}
Destroy(go1); // Destroy the object directly go1
Destroy(go2,3); // stop 3 Destroy the object in seconds go2
7、 ... and : Find game objects
Find game objects by name
GameObject cube1=GameObject.Find("Player");
GameObject cube2=GameObject.FindWithTag("Player");
// There are three ways to get game objects :
//1. Get... By object name :objCube=GameObject.Find("Cube");
// for example :
private var objCube:GameObject;
private var isCubeRoate=false;
function Start () {
objCube=GameObject.Find("Cube");
}
function Update(){
if(isCubeRoate){
objCube.transform.Rotate(0.0f,Time.deltaTime*200,0.0f);
}
}
function OnGUI(){
if(GUILayout.Button(" rotate ",GUILayout.Height(50))){
isCubeRoate=true;
}
}
//2. adopt tag Tag to get a single GameObject :objCube=GameObject.FindWithTag("Finish");
//3. Get multiple groups of game objects through the game tag :objCube=GameObject.FindGameObjectsWithTag("Finish");
8、 ... and : add to 、 Get components
//1、 hold Move This script is added to cube On this game object
cube.AddComponent("Move");
//2、 Add a rigid body to the game object
cube.AddComponent("Rigidbody");
//3、 Add a sphere Collider to the game object
cube.AddComponent("BoxCollider");
//1、 Get script components Move
Move m=cube.GetComponent<Move>();
//2、 Get the rigid body component
Rigidbody r=cube.GetComponent<Rigidbody>();
Nine :Random
float a=Random.value; // return 0.0( Include ) To 1.0( Include ) Number between .
int b=Random.Range(0,100) ; // Include the smallest but not the largest
float c=Random.Range(0.0f,5.5f); // Including maximum and minimum
Ten :Input
- Mouse events
GetMouseButton(0): Press the left mouse button and don't move , The program will run all the time , Release the left key to stop the program .
GetMouseButton(2): Press the middle mouse button and don't move , The program will run all the time , Release the middle key to stop the program .
GetMouseButton(1): Press the right mouse button and don't move , The program will run all the time , Release the right button to stop the program .
GetMouseButtonDown(0): When you press the left mouse button , The program runs once
GetMouseButtonDown(1): When you press the right mouse button , The program runs once
GetMouseButtonUp(2): When you press the middle mouse button , The program does not run , When you release the middle key , The program runs once .
if(Input.GetMouseButton(0)){
Execute statement ;
}
2. Keyboard events
GetKey When the key specified by name is pressed and held by the user, it returns true
GetKeyDown When the user presses the key with the specified name, the frame returns true.
GetKeyUp Returns... At the frame where the user releases the key with a given name true.
GetAxis("Horizontal") and GetAxis("Vertical") Horizontal and vertical axes
if(Input.GetKey("Down")){
Execute statement ;
}
// Case study : Use the arrow keys or WASD To simulate the movement of objects
float speed = 3f;
void Update () {
//float h = Time.deltaTime * speed;
// Press down WSAD Key to move the game object back and forth, left and right
/*if (Input.GetKey(KeyCode.A))
{
transform.Translate(new Vector3(-h, 0, 0));
}
if (Input.GetKey(KeyCode.D))
{
transform.Translate(new Vector3(h, 0, 0));
}
if (Input.GetKey(KeyCode.W))
{
transform.Translate(new Vector3(0, 0, h));
}
if (Input.GetKey(KeyCode.S))
{
transform.Translate(new Vector3(0, 0, -h));
}*/
//Horizontal
//Vertical
float h= Input.GetAxis("Horizontal")*Time.deltaTime*speed;
float v = Input.GetAxis("Vertical") * Time.deltaTime * speed;
//transform.Translate(h, 0, v);
transform.Translate(new Vector3(h, 0, v));
}
3. Custom buttons
GetButton Return... According to the button name true When the corresponding virtual button is pressed .
GetButtonDown The frame in which the virtual button of a given name is pressed returns true.
GetButtonUp Returns... When the user releases the virtual button with the specified name true.
// Case study : Left click , Add a force to the object
if (Input.GetButtonDown("Fire1"))
{
GameObject go = Instantiate(cube);
Rigidbody r = go.GetComponent<Rigidbody>();// Get rigid body components from preset bodies
r.AddForce(0,0,10000);// Add force to the preset body
}
11、 ... and : coroutines
Collaborative process , That is, when the main program is running, another logic processing is started at the same time to coordinate the execution of the current program . let me put it another way , To start a collaborative program is to start a thread .
Use StartCoroutine(string methodName) You can start a thread .
Yield A statement is a special type of Return( return ) sentence , It ensures that the next time the function is executed , Not from scratch , But from Yield Start at statement .
Synergetic process is actually a IEnumerator( iterator ). The iterator method runs to yield return When the sentence is , Will return an expression and keep the current position in the code . The next time the iterator function is called, execution restarts from that location .
// Case study : every other 3 Second clone a cube
public GameObject cube;
void Start () {
StartCoroutine("NewCube");
}
IEnumerator NewCube()
{
while (true)
{
Instantiate(cube);
yield return new WaitForSeconds(3f);
}
}
Part of the exercise :
//2、 Click the left mouse button to clone a sphere bullet ,5 The bullet will be destroyed in seconds
public GameObject obj;
GameObject g1;
void Update () {
if (Input .GetButtonDown("Fire1"))
{
g1=Instantiate(obj)as GameObject;
}
Destroy(g1,5);
}
//2、 use yield Implement game objects 3 Second press X The axis moves in the positive direction 2 rice
public GameObject cube;
void Start () {
StartCoroutine(BB());
}
IEnumerator BB()
{
while (true)
{
yield return new WaitForSeconds(3f);
Instantiate(cube, Vector3.right * Time.time * 2, Quaternion.identity);
}
}
//4、 use Time Class implementation 5 Second countdown ( Show... On the page )
public float a = 5f;
void Start () {
}
void Update () {
if (a >= 0)
{
print((int)a);
}
a -= Time.deltaTime;
}
//5. Press up, down, left and right (WSAD) key , Let the game object move back and forth, left and right
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
transform.Translate(h, 0, v);
//6、 use Random Class generates a four digit verification code ( No repetition )
void Start () {
int a = Random.Range(0, 9);
int b = Random.Range(0, 9);
int c = Random.Range(0, 9);
int d = Random.Range(0, 9);
if (a!=b&&a!=c&&a!=d&&b!=c&&b !=d&&c !=d)
{
print(a+""+b+""+c+""+d);
}
}
//7、 Script Test Access script Test2 What's in it ( Find game objects by name )
public class Test : MonoBehaviour {
public float time = 3f;
}
public class Test2 : MonoBehaviour {
GameObject cube;
void Start() {
cube = GameObject.Find("Cube");
Test t = GetComponent<Test>();
print(t.time);
}
}
//8、 Click the left mouse button to make the object move towards Z The axis moves in the positive direction 3 rice , Click the right mouse button to make the object circle Y Shaft rotation
void Update () {
if (Input .GetButtonDown("Fire1"))
{
transform.Translate(Vector3.forward*Time.time*3);
}
else if (Input .GetButtonDown("Fire2"))
{
transform.Rotate(new Vector3(0, 1, 0));
}
}
//9、 Click the left mouse button to XZ Launch the ball diagonally
void Update () {
if (Input.GetButtonDown("Fire1"))
{
GameObject g = Instantiate(sq);
Rigidbody r = g.AddComponent<Rigidbody>();
r.AddForce(1000, 0, 10000);
}
}
//10、3 The second countdown enlarges the sphere 2 times , And then again 3 The second countdown makes the sphere the same
time -= Time.deltaTime;
if (time <= 3)
{
transform.localScale = new Vector3(2, 2, 2);
if (time <= 0)
{
transform.localScale = new Vector3(1, 1, 1);
}
}
//11、 Brick wall : Dynamic generation 10 That's ok 10 Columns of walls , Click the left mouse button to launch a sphere to the wall ,3 Seconds later, the sphere disappears
public GameObject cube;
public GameObject sq;
// Use this for initialization
void Start () {
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
Instantiate(cube, new Vector3(i, j, 0), Quaternion.identity);
}
}
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Fire1"))
{
GameObject g = Instantiate(sq);
Rigidbody r = g.AddComponent<Rigidbody>();
r.AddForce(0,0,10000);
Destroy(sq, 3);
}
}
//12、 Click the left mouse button to clone a bullet , Then let the bullet fly straight ahead
if (Input.GetButtonDown("Fire1"))
{
GameObject g = Instantiate(sq);
Rigidbody r = g.AddComponent<Rigidbody>();
r.AddForce(0, 0, 100000);
}
//13. Game begins 3 Seconds later , Different positions in the game scene (x:0--10 z:2--8) Random simultaneous cloning 3 A game object
void Start()
{
StartCoroutine(AA());
}
IEnumerator AA()//15.
{
while (true)
{
yield return new WaitForSeconds(3f);
for (int i = 0; i < 3; i++)
{
int x = Random.Range(0, 10);
int z = Random.Range(2, 8);
Instantiate(cube, new Vector3(x, 0, z), Quaternion.identity);
}
}
}
版权声明
本文为[C # primary advanced]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220621093628.html
边栏推荐
- Talent Plan 学习营初体验:交流+坚持 开源协作课程学习的不二路径
- Student achievement management
- Docker拉取mysql并连接
- 打卡:4.22 C语言篇 -(1)初识C语言 - (11)指针
- MySql关键字GROUP_CONCAT,组合连接查询
- [MySQL] left Function | Right Function
- Seminar playback video: how to improve Jenkins' ability to become a real Devops platform
- Use of ADB command [1]
- JS inheritance
- Log4net is in Net core usage
猜你喜欢

QT dynamic translation of Chinese and English languages
![[Mysql] LEFT函數 | RIGHT函數](/img/26/82e0f2280de011636c26931a74e749.png)
[Mysql] LEFT函數 | RIGHT函數

Super easy to use asynchronous export function of Excel

QT learning summary

C WPF UI framework mahapps switching theme

Experiment 5 components and event handling

Visual programming - Experiment 1

. net webapi access authorization mechanism and process design (header token + redis)

Why is bi so important to enterprises?

Quartz. Www. 18fu Used in net core
随机推荐
QT dynamic translation of Chinese and English languages
MySQL keyword group_ Concat, combined connection query
Chapter 9 of C language programming (fifth edition of Tan Haoqiang) analysis and answer of exercises for users to establish their own data types
Fiddler use
全新的ORM框架——BeetlSQL介绍
Mysql database, inconsistent index character set, slow SQL query, interface timeout
Chapter 8 of C language programming (fifth edition of Tan Haoqiang) is good at using pointer exercises to analyze and answer
第四次作业
Téléchargement en vrac de fichiers - téléchargement après compression
. net core current limiting control - aspnetcoreratelimit
Log4net is in Net core usage
. net 5 Web custom middleware implementation returns the default picture
It can receive multiple data type parameters - variable parameters
一套组合拳,打造一款 IDEA 护眼方案
TCP three handshakes and four waves
C WPF UI framework mahapps switching theme
xutils3修改了我提报的一个bug,开心
C introduction of variable parameter params
2022a special equipment related management (elevator) work license question bank and simulation examination
Iotos IOT middle platform is connected to the access control system of isecure center