Video tutorial: https://www.bilibili.com/video/BV12s411g7gU?p=122
Table of contents
GetSiblingIndex、SetSiblingIndex
Transform
Object Position, Rotation and Scale
Every object in the scene has a Transform, which is used to store and manipulate the object's position, rotation, and scale. Each Transform can have a parent, capable of applying position, rotation and scaling hierarchically
Transform.position : relative to the origin of the world coordinate system
Transform.localPosition : Relative to the pivot point of the parent object, if there is no parent, it is the same as Transform.position
Transform.localScale : Relative to the scaling of the parent object
ps: The Position, Rotation, and Scale in the Inspector panel are all relative to the parent object
Set the Inspector panel to debug
Transform.lossyScale : Global scaling of the object (read-only)
ps: lossyScale = self scaling ratio * parent object scaling ratio; suppose the parent object localScale is 2, the child object localScale is 3, then its lossyScale is 6
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TransformDemo : MonoBehaviour
{
public Transform root;
void OnGUI()
{
if (GUILayout.Button("foreach--transform"))
{
foreach (Transform child in this.transform)
{
print(child.name);
}
}
if (GUILayout.Button("root"))
{
print(this.transform.parent);
}
if (GUILayout.Button("Space.World--setParent"))
{
//当前物体的位置视为世界坐标
this.transform.SetParent(root);
}
if (GUILayout.Button("Self.World--setParent"))
{
//当前物体的位置视为localScale
this.transform.SetParent(root, false);
}
if (GUILayout.Button("DetachChildren"))
{
this.transform.DetachChildren();
}
if (GUILayout.Button("Find"))
{
print(this.transform.Find("Cube"));
}
if (GUILayout.Button("childCount"))
{
int count = this.transform.childCount;
for (int i = 0; i < count; i++)
{
print(transform.GetChild(i));
}
}
if (GUILayout.Button("Self.World--Z+1"))
{
this.transform.Translate(0, 0, 1);
}
if (GUILayout.Button("Space.World--Z+1"))
{
this.transform.Translate(0, 0, 1, Space.World);
}
if (GUILayout.Button("Self.World--Rotate_X+1"))
{
this.transform.Rotate(10, 0, 0);
}
if (GUILayout.Button("Space.World--Rotate_X+1"))
{
this.transform.Rotate(10, 0, 0, Space.World);
}
if (GUILayout.RepeatButton("RotateAround"))
{
this.transform.RotateAround(Vector3.zero, Vector3.up, 1);
}
}
}
foreach--transform button: Get the object name of the direct (first generation) child object
There is a parent-child relationship as shown in the figure below, child 1, child 2 and child 3 are the direct (first generation) child objects of the parent object parent, and _child 1 and _child 2 are its indirect (second generation) child objects; hang TransformDemo Loaded to the parent object parent
After running, click the foreach--transform button, and you can observe that the console outputs the object name of the first generation child object
Transform.parent : Get the Transform component of the root object
root button: output the object name of the root object (similar to the root node in the tree); if there is also the parent-child relationship diagram above, mount the script to child 1 and _child 1 respectively and click the root button to observe the console The output is all parent
Transform.SetParent : Set the parent of the current Transform
Space.World--setParent button and Self.World--setParent button: both functions are to set the current game object as a child object of another game object (set parent), the difference lies in the position after setting the parent-child relationship
In the Space.World --setParent button
this.transform.SetParent(root)
Equivalent to
this.transform.SetParent(root,true)
The meaning of the above code is that after setting the current object as a sub-object of root, the position of the current object relative to the origin of the world coordinate system is converted to localPosition relative to root, that is, the position of the current object in the world coordinate system does not change
As shown in the figure below root(15,0,0), Cube(15,0,5), the position of the world coordinates in the Cube is still (15,0,5) after execution, and the localPosition relative to the root is (0,0, 5)
And in the Self.World--setParent button
this.transform.SetParent(root, false)
The meaning of this code is that after the current object is set as a child object of root, the position of the current object relative to the origin of the world coordinate system is taken as the localPosition relative to root, that is, the position of the current object in the world coordinate system is equal to that of the parent object in the world coordinates The position in + the previous position of the current object in world coordinates (the vector sum of the two)
As shown in the figure below root(15,0,0), Cube(15,0,5), the position of the world coordinates in the Cube after execution is (30,0,5), and the localPosition relative to the root is (15,0,5 )
Transform.DetachChildren : Detach all direct (first generation) children (child objects) of the parent
DetachChildren button: If there is a parent-child structure like in foreach--transform, the script is also mounted for the parent. After running, click the DetachChildren button, and all direct children of the parent will release the relationship with the parent parent; that is, child 1 and child will be separated 2. Child 3, while _child 1 and _child 2 are still children of child 1 and child 2 respectively
Transform.Find : Find and return the child with the corresponding name
Find button: Finds and returns a child named Cube among all immediate children
ps: The format that can be written as the following path represents the parent-child hierarchy
transform. Find("LeftShoulder/Arm/Hand/Finger");
Transform.childCount : Returns the number of immediate (first generation) children of the parent
Transform.GetChild : Returns the corresponding immediate (first generation) child by index
childCount button: Similar to the foreach--transform button, but can return the corresponding first-generation child items by index; also take the parent-child structure in foreach--transform as an example, mount the script for the parent, run and click the childCount button, you can Observe that the console outputs the first-generation children of the parent parent
Transform.Translate : Move the object according to world coordinates or local coordinates
Self.World--Z+1 button and Space.World--Z+1: Both functions are to make the Z axis of the object +1, but the reference system is different. Self.World--Z+1 refers to the object The own coordinates and Space.World--Z+1 refer to the world coordinates
In Self.World--Z+1
this.transform.Translate(0, 0, 1)
Equivalent to
this.transform.Translate(0, 0, 1, Space.Self)
Regarding the difference between self coordinates and world coordinates, as shown in the figure below
Transform.Rotate : Rotate the object according to world coordinates or local coordinates, usually providing rotation with Euler angles instead of quaternions
Self.World--Rotate_X+1 button and Space.World--Rotate_X+1 button, both functions are to select 1 degree around the X axis of the object, and the difference also lies in the different reference systems
Transform.RotateAround : Rotates the object around a rotation axis passing through a point in world coordinates
RotateAround button: Make the object rotate around the rotation axis passing through the origin of the coordinates (0,1,0)
Use recursion to find subkeys with unknown hierarchy
Scripting TransformHelper
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TransformHelper : MonoBehaviour
{
public string target;
void OnGUI()
{
if (GUILayout.Button("Recursion_Find"))
{
print(Recursion_Find(this.transform, target));
}
}
Transform Recursion_Find(Transform root, string name)
{
Transform target = root.transform.Find(name);
if (target) return target;
if (root.transform.childCount == 0) return null;
foreach (Transform child in root.transform)
{
if (Recursion_Find(child, name) != null)
{
return Recursion_Find(child, name);
}
}
return null;
}
}
Change the parent-child structure displayed in foreach--transform, and add a Cube named target in child 3 as the target of the search
After mounting the script on the parent and setting parameters, click the Recursion_Find button in the upper left corner of the Game panel to run the scene, and you can observe that the console outputs the sub-item target
GameObject
GameObject.activeInHierarchy : The actual active state of the object
GameObject.activeSelf : The active state of the object itself (the state in the Inspector panel, and it is read-only)
As shown in the figure below, the parent child 1 is disabled and the child _child 1 is disabled, but in fact the child _child 1 is still enabled in the Inspector panel
In the above case, activeInHierarchy of child _child 1 is false and activeSelf is true
GameObject.SetActive : enable/disable object
GameObject.AddComponent<T>() : Add component T to the game object
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameObjectDemo : MonoBehaviour
{
void OnGUI()
{
if (GUILayout.Button("添加光源"))
{
GameObject lightGO = new GameObject();
Light light = lightGO.AddComponent<Light>();
light.color=Color.red;
light.type=LightType.Point;
}
}
}
ps: There is no need to use the new keyword to create an object when mounting a component in a script, because the execution of the AddComponent method includes the process of using new for construction
Mount the script for a certain game object. After running, click the "Add Light Source" button in the upper left corner of the Game panel, and you will find that a game object named New Game Object that mounts the light component has been added to the creation.
GameObject.Find("game object name") : Find objects in the scene by name (use with caution, this method will try to traverse every game object in the scene)
GameObject.FindGameObjectWithTag("tag name") : returns the first object that uses this tag (single)
GameObject.FindGameObjectsWithTag("tag name") : returns all objects (array) that use this tag
Object
Object.Destroy(Object obj, float delay= 0.0F) : Remove GameObject, component or resource
obj | object to be destroyed |
delay | (Optional) The delay before destroying the object |
Object.DestroyImmediate : Destroy the game object immediately (it is recommended to use Destroy instead)
Object.DontDestroyOnLoad : When loading a new Scene, do not destroy the Object
Object.FindObjectOfType<T>() : returns the first active object of type T (single)
Object.FindObjectsOfType<T>() : Returns all objects (arrays) of type T
Find the enemy with the lowest health
Scripting Enemy
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public float hp;
}
Create three game objects in the scene named Enemy 1, Enemy 2, and Enemy 3, mount script Enemy for them and set different Hp
After writing the script Find_Enemies and attaching it to a game object, run the scene and click the "Find the enemy with the lowest HP" button
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Find_Enemies : MonoBehaviour
{
void OnGUI()
{
if (GUILayout.Button("查找血量最低的敌人"))
{
var enemy_list = Object.FindObjectsOfType<Enemy>();
Enemy min = enemy_list[0];
foreach (Enemy i in enemy_list)
{
if (i.hp < min.hp)
{
min = i;
}
}
print(min);
}
}
}
Find the nearest enemy
Set Enemy 1, Enemy 2, and Enemy 3 to different positions
Add code in script Find_Enemies
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Find_Enemies : MonoBehaviour
{
public Transform target;
void OnGUI()
{
//查找血量最低的敌人
if (GUILayout.Button("查找距离最近的敌人"))
{
var enemy_list = Object.FindObjectsOfType<Enemy>();
Enemy closer = enemy_list[0];
float minDist = Vector3.Distance(closer.transform.position, target.position);
foreach (Enemy i in enemy_list)
{
float newDist = Vector3.Distance(i.transform.position, target.position);
if (newDist < minDist)
{
closer = i;
minDist = newDist;
}
}
print(closer);
}
}
}
Create an empty object named target as a distance reference, that is, which Enemy object is the closest to the target; run the scene and click the "Find the nearest enemy" button
Vector3.magnitude : Returns the magnitude of the vector (read-only)
ps:new Vector3(x,y,z).magnitude=(x^2+y^2+z^2)^(1/2)
Vector3.sqrMagnitude : Returns the square of the magnitude of the vector (read-only)
ps:new Vector3(x,y,z).sqrMagnitude=x^2+y^2+z^2
Vector3.Distance(Vector3 a, Vector3 b) : returns the distance between a and b, same as (ab).magnitude
GetComponentInParent
Component.GetComponentInParent<T>() : Find the T component from the current game object, if there is one, return it directly, if not, traverse the parent up until it is found
LookAt
Transform.LookAt : Make the current object's forward vector point to the target position
GetSiblingIndex、SetSiblingIndex
Transform.GetSiblingIndex : Get sibling (shares an immediate parent and is at the same level) index
Transform.SetSiblingIndex : set/change sibling index
Instantiate
Object.Instantiate : Clone the object and return