当前位置:网站首页>Unity script API - component component

Unity script API - component component

2022-07-04 15:22:00 @Night Charm

  Common methods :

    GetComponent: Get references of other component types of the current object .
    GetComponents: Get all component references of the current object .
    GetComponentsInChildren: Find components of the specified type ( Start with yourself , And search all descendants )
    GetComponentInChildren: Find components of the specified type ( Start with yourself , And search all descendants , If you find the first one that meets the condition, it will end )
    GetComponentsInParent: Find components of the specified type ( Start with yourself , And search all ancestors )

  The code is as follows :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// Component  class   It provides the function of finding components ( From oneself 、 From offspring 、 From the ancestors ) Functions of components 
/// </summary>
public class ComponentDemo : MonoBehaviour
{
    private void OnGUI()
    {
        if (GUILayout.Button("transform")) 
        { 
            this.transform.position = new Vector3(0,0,10);
        }

        if (GUILayout.Button("GetComponent"))
        {
            this.GetComponent<MeshRenderer>().material.color = Color.red;
        }

        if (GUILayout.Button("GetComponents"))
        {
            // Get the current component 
            var allComponent = this.GetComponents<Component> ();
            foreach (var component in allComponent)
            { 
                Debug.Log(component.GetType());
            }
        }

        if (GUILayout.Button("GetComponentsInChildren"))
        {
            // Gets the specified type component of the descendant object ( Start with yourself )
            var allComponent = this.GetComponentsInChildren<MeshRenderer>();
            foreach (var component in allComponent)
            {
                component.material.color = Color.red;
            }
        }

        if (GUILayout.Button("GetComponentsInParent"))
        {
            // Gets the specified type component of the predecessor object ( Start with yourself )
            var allComponent = this.GetComponentsInParent<MeshRenderer>();
            foreach (var component in allComponent)
            {
                component.material.color = Color.red;
            }
        }
    }
}

原网站

版权声明
本文为[@Night Charm]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041413411091.html