banner
paofan

paofan

欢迎来到我的个人主页!我是泡饭~喵~🐱
steam_profiles
bilibili
github

unity獲取父子物件腳本

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

public class Lesson3 : MonoBehaviour
{
    public Lesson3 otherLesson3;

    // 開始在第一幀更新之前被調用
    void Start()
    {
        #region 知識點一 重要成員
        //1.獲取依附的GameObject
        print(this.gameObject.name);
        //2.獲取依附的GameObject的位置信息
        //得到對象位置信息
        print(this.transform.position);//位置
        print(this.transform.eulerAngles);//角度
        print(this.transform.lossyScale);//縮放大小
        //這種寫法和上面是一樣的效果 都是得到依附的對象的位置信息
        //this.gameObject.transform

        //3.獲取腳本是否激活
        this.enabled = false;

        //獲取別的腳本對象 依附的gameobject和 transform位置信息
        print(otherLesson3.gameObject.name);
        print(otherLesson3.transform.position);
        #endregion

        #region 知識點二 重要方法
        //得到依附對象上掛載的其它腳本

        //1.得到自己掛載的單個腳本
        //根據腳本名獲取
        //獲取腳本的方法 如果獲取失敗 就是沒有對應的腳本 會默認返回空
        Lesson3_Test t = this.GetComponent("Lesson3_Test") as Lesson3_Test;
        print(t);
        //根據Type獲取
        t = this.GetComponent(typeof(Lesson3_Test)) as Lesson3_Test;
        print(t);
        //根據泛型獲取 建議使用泛型獲取 因為不用二次轉換
        t = this.GetComponent<Lesson3_Test>();
        if( t != null )
        {
            print(t);
        }
        
        //只要你能得到場景中別的對象或者對象依附的腳本
        //那你就可以獲取到它的所有信息

        //2.得到自己掛載的多個腳本
        Lesson3[] array = this.GetComponents<Lesson3>();
        print(array.Length);
        List<Lesson3> list = new List<Lesson3>();
        this.GetComponents<Lesson3>(list);
        print(list.Count);

        //3.得到子對象掛載的腳本(它默認也會找自己身上是否掛載該腳本)
        //函數是有一個參數的 默認不傳 是false 意思就是 如果子對象失活 是不會去找這個對象上是否有某個腳本的
        //如果傳true 即使失活 也會找
        //得子對象 挂載腳本 單個
        t = this.GetComponentInChildren<Lesson3_Test>(true);
        print(t);
        //得子對象 挂載腳本 多個
        
        Lesson3_Test[] lts = this.GetComponentsInChildren<Lesson3_Test>(true);
        print(lts.Length);
        
        List<Lesson3_Test> list2 = new List<Lesson3_Test>();
        this.GetComponentsInChildren<Lesson3_Test>(true, list2);
        print(list2.Count);

        //4.得到父對象掛載的腳本(它默認也會找自己身上是否掛載該腳本)
        t = this.GetComponentInParent<Lesson3_Test>();
        print(t);
        lts = this.GetComponentsInParent<Lesson3_Test>();
        print(lts.Length);
        //它也有list的 省略不寫了 和上面是一樣的套路

        //5.嘗試獲取腳本
        Lesson3_Test l3t;
        //提供了一個更加安全的 獲取單個腳本的方法 如果得到了 會返回true
        //然後再來進行邏輯處理即可
        if(this.TryGetComponent<Lesson3_Test>(out l3t))
        {
            //邏輯處理
        }

        #endregion
    }

    // 更新每幀調用一次
    void Update()
    {
        
    }
}
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。