Component
helloz 4/3/2024 Unity3d
unity component
https://docs.unity3d.com/ScriptReference/Component.html (opens new window)
functions
functions | parameter | describe |
---|---|---|
gameObject:AddComponent(type) | 1.typeof(UnityEngine.Animation) return:Component | Use typeof to get the type, if the addition is successful, it will return the component type |
gameObject:GetComponent(type) | 1.typeof(UnityEngine.Animation) return:Component | |
gameObject:GetComponent(string) | 1.class name return: Component | example: Get the 'Animation' component, if the object exists "UnityEngine.Animation", it will return the Animation class |
gameObject:GetComponents(type) | 1.typeof(UnityEngine.Animation) return:Component[] |
Correct Way to Check for Missing Components in XLua (Unity 6+)
Why does GetComponent return userdata instead of nil?
Use == nil and Equals(nil) to verify:
local ani1 = gameObject:GetComponent(typeof(UnityEngine.Animation))
if ani1 == nil or ani1:Equals(nil) then
print("Component does not exist")
else
print("Component exists:", Animation)
end
--or use IsExist \ IsNil to check
if IsNil(ani1) then
print("Component does not exist")
end
if IsExist(ani1) then
print("Component exists:", Animation)
end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
code
-- AddComponent
local ani1 = gameObject:AddComponent(typeof(UnityEngine.Animation))
-- GetComponent
local ani1 = gameObject:GetComponent(typeof(UnityEngine.Animation))
-- GetComponentsInChildren
local child_ani = gameObject:GetComponentInChildren(typeof(UnityEngine.Animation))
local child_ani_array = gameObject:GetComponentsInChildren(typeof(UnityEngine.Animation))
-- GetComponentsInParent
local parent_ani = gameObject:GetComponentInParent(typeof(UnityEngine.Animation))
local parent_ani_array = gameObject:GetComponentsInParent(typeof(UnityEngine.Animation))
local ani2 = gameObject:GetComponent('Animation')
--or-- ani = transform:GetComponent('Animation')
ani:Play("idle")
--获取数组
local mytf=TransformEx.MyPlayerTransform()
local items=mytf:GetComponents(typeof(UnityEngine.MonoBehaviour))
--or --items=mytf.gameObject:GetComponents(typeof(UnityEngine.MonoBehaviour))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23