MonoBehavior中的重要内容

public class MonoIm : MonoBehaviour
{
    public MonoIm otherMono;
    // Start is called before the first frame update
    void Start()
    {
        #region 重要成员
        //获取依附的GameObj=>gameObject
        print(gameObject.name);
        //获取依附的GameObj的位置信息
        print(transform.position);//位置
        print(transform.eulerAngles);//角度
        print(transform.lossyScale);//缩放大小
        //激活脚本
        enabled = true;
        //失活脚本
        enabled = false;
        //获取别的脚本对象依附的GameObj
        print(otherMono.gameObject.name);
        #endregion
        #region 重要方法
        //得到依附对象上挂载的其他脚本
        //得到自己挂载的单个脚本
        //根据脚本名获取
        //如果没有对应的脚本会返回null
        L3Test t = GetComponent("L3Test") as L3Test;
        print(t);
        //根据Type获取
        t=GetComponent(typeof(L3Test)) as L3Test; 
        print(t);
        //根据泛型获取,不用二次转换
        t=GetComponent<L3Test>();
        print(t);
        //只要你能得到场景中别的对象或者对象依附的脚本,那你就可以获得它得所有信息
        //得到自己挂载的多个脚本(一个对象上依附的多个同类型脚本)
        MonoIm[] array = GetComponents<MonoIm>();
        print(array.Length);
        List<MonoIm> list = new List<MonoIm>();
        GetComponents<MonoIm>(list);
        print(list.Count);
        //得到子对象挂载的脚本(默认也会找自己身上是否挂载该脚本)默认不找失活的
        //如果传入true就寻找失活的GetComponentInChildren<L3Test>(True)
        t = GetComponentInChildren<L3Test>();
        print(t);
        //以数组形式得多个挂载脚本
        L3Test[] list2 = GetComponentsInChildren<L3Test>();
        print(list2.Length);
        //以list形式
        List<L3Test> list3 = new List<L3Test>();
        GetComponentsInChildren<L3Test>(true,list3);
        print(list3.Count);
        //得到父对象挂载脚本
        t = GetComponentInParent<L3Test>();
        print(t);
        L3Test[] list4 = GetComponentsInParent<L3Test>();
        print(list4.Length);
        List<L3Test> list5 = new List<L3Test>();
        GetComponentsInParent<L3Test>(true,list5);
        print(list5.Count);
        //尝试获取脚本
        L3Test t2;
        //提供了一个更加安全的获取单个脚本的方法,如果得到了会返回True
        if(TryGetComponent<L3Test>(out t2))
        {
            //进行逻辑处理
        }
        #endregion
    }

}
posted @ 2025-03-15 13:48  cannedmint  阅读(15)  评论(0)    收藏  举报