Small white _unity engine _ Get components and add components

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.