1 #regionGet components2 //1. Getting components by generic means3Boxcollider BC = gameobject.getcomponent<boxcollider>();4Gameobject.getcomponent<meshrenderer> (). Material.color =color.red;5 6 //2. Scripts are also built to get the same method7Newbehaviourscript ns = gameobject.getcomponent<newbehaviourscript>();8 9 //3. Get single or multiple components (or scripts) from the object itself or its sub-objects (son, grandson, grandson)TenMeshrenderer ms = Gameobject.getcomponentinchildren<meshrenderer>(); OneMs.material.color =Color.Blue; A //get a list of sub-object components (including the object itself and all sub-objects below) -meshrenderer[] Mrs = Gameobject.getcomponentsinchildren<meshrenderer>(); - the - //3. Get single or multiple components or scripts from the parent object (including the object itself, its parent object (parent, grandfather, ancestor) -Meshrenderer Mr = Gameobject.getcomponentinparent<meshrenderer>(); - //get the list of components in the parent class +meshrenderer[] MREs = gameobject.getcomponentsinparent<meshrenderer>(); - intCount =MREs. Length; + A at - #endregion
To add a component:
1. Adding components dynamically
1 // dynamically add related components or scripts 2 rigidbody RB = gameobject.addcomponent<rigidbody> ( );
2. Adding components by extension Editor [Requirecomponent]
Note: The code executed by the extended editor must be in the editor state
For example, to add a rigid component Rigidbody
[Requirecomponent (typeof (Rigidbody)]) adds a rigid body when mounting a script, not the public class that is added at execution time Newbehaviourscript2:monobehaviour {}
Execute in Edit state, add a rigid body component when adding a script
Small white _unity engine _ Get components and add components