1. 程式人生 > >Unity 根據Transform、GameObject和Tag獲取子物件集合

Unity 根據Transform、GameObject和Tag獲取子物件集合

       因為專案中難免要多次進行獲取子物件或者子物件的集合,所以同事之前寫了一個單獨的類,用來做這些操作。然後再實際的專案中,只需要使用 transform 或者 gameobject  呼叫這些方法就可以快速的得到這些資料,而並不需要自己在每個單獨的類裡面都寫上一遍。

       不想偷懶的程式設計師不是好的程式設計師。程式碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;


public static partial class ExtentionMethod
{
    /// <summary>
    /// 獲取子物件變換集合
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static List<Transform> GetChildCollection(this Transform obj)
    {
        List<Transform> list = new List<Transform>();
        for (int i = 0; i < obj.childCount; i++)
        {
            list.Add(obj.GetChild(i));
        }
        return list;
    }

    /// <summary>
    /// 獲取子物件集合
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static List<GameObject> GetChildCollection(this GameObject obj)
    {
        var list = obj.transform.GetChildCollection();
        return list.ConvertAll(T => T.gameObject);
    }

    public static Transform GetRootParent(this Transform obj)
    {
        Transform Root = obj.parent;
		while(Root.parent != null)
        {
			//Root = Root.root;   //transform.root,方法可以直接獲取最上父節點。
			Root = Root.parent;
        }
		return Root;
    }

	/// <summary>
	/// 把源物件身上的所有元件,新增到目標物件身上
	/// </summary>
	/// <param name="origin">源物件</param>
	/// <param name="target">目標物件</param>
    public static void CopyComponent(GameObject origin, GameObject target)
    {
        var originComs = origin.GetComponents<Component>();
        foreach (var item in originComs)
        {
            target.AddComponent(item.GetType());
        }
    }

    /// <summary>
    /// 改變遊戲指令碼
    /// </summary>
    /// <param name="origin"></param>
    /// <param name="target"></param>
    public static void ChangeScriptTo(this MonoBehaviour origin, MonoBehaviour target)
    {
        target.enabled = true;
        origin.enabled = false;
    }


    /// <summary>
    /// 從當前物件的子物件中查詢,返回一個用tag做標識的活動的遊戲物體的連結串列.如果沒有找到則為空. 
    /// </summary>
    /// <param name="obj">物件Transform</param>
    /// <param name="tag">標籤</param>
    /// <param name="transList">結果Transform集合</param> // 對一個父物件進行遞迴遍歷,如果有子物件的tag和給定tag相符合時,則把該子物件存到 連結串列陣列中
    public static void FindGameObjectsWithTagRecursive(this Transform obj, string tag, ref List<Transform> transList)
    {
        foreach (var item in obj.transform.GetChildCollection())
        {
			// 如果子物件還有子物件,則再對子物件的子物件進行遞迴遍歷
            if (item.childCount > 0)
            {
                item.FindGameObjectsWithTagRecursive(tag, ref transList);
            }

            if (item.tag == tag)
            {
                transList.Add(item);
            }
        }
    }

    public static void FindGameObjectsWithTagRecursive(this GameObject obj, string tag, ref List<GameObject> objList)
    {
        List<Transform> list = new List<Transform>();
        obj.transform.FindGameObjectsWithTagRecursive(tag, ref list);

        objList.AddRange(list.ConvertAll(T => T.gameObject));
    }

    /// <summary>
    /// 從父物件中查詢元件
    /// </summary>
    /// <typeparam name="T">元件型別</typeparam>
    /// <param name="com">物體元件</param>
    /// <param name="parentLevel">向上查詢的級別,使用 1 表示與本物件最近的一個級別</param>
    /// <param name="searchDepth">查詢深度</param>
    /// <returns>查詢成功返回相應元件物件,否則返回null</returns>
    public static T GetComponentInParent<T>(this Component com, int parentLevel = 1, int searchDepth = int.MaxValue) where T : Component
    {
        searchDepth--;

        if (com != null && searchDepth > 0)
        {
            var component = com.transform.parent.GetComponent<T>();
            if (component != null)
            {
                parentLevel--;
                if (parentLevel == 0)
                {
                    return component;
                }
            }

            return com.transform.parent.GetComponentInParent<T>(parentLevel, searchDepth);
        }

        return null;
    }    
}



相關推薦

Unity 根據TransformGameObjectTag獲取物件集合

       因為專案中難免要多次進行獲取子物件或者子物件的集合,所以同事之前寫了一個單獨的類,用來做這些操作。然後再實際的專案中,只需要使用 transform 或者 gameobject  呼叫這些方法就可以快速的得到這些資料,而並不需要自己在每個單獨的類裡面都寫上一遍

JQuery動畫——.trim()去空格.get().index()獲取DOM元素

JQuery動畫 .trim()去空格、.get()和.index()獲取DOM元素1 .trim()函數用於去除字符串兩端的空白字符,沒有多余的參數用法2 移除字符串開始和結尾處的所有換行符,空格(包括連續的空格)和制表符(tab),如果這些空白字符在字符串中間時,它們將被保留,不會被移除

CSS動畫transformtransitionanimation的區別

strong skew init mat matrix 開始 ansi 扭曲 觸發 CSS3屬性中關於制作動畫的三個屬性:Transform,Transition,Animation。 1、transform:描述了元素的靜態樣式,本身不會呈現動畫效果,可以對元素進行 旋轉

CSS3中和動畫有關的屬性transformtransition animation

     transition-delay是用來指定一個動畫開始執行的時間,也就是說當改變元素屬性值後多長時間開始執行transition效果,取 值:<time>為數值,單位為s(秒),它的使用和transition-duration極其相似,也可以作用於所有元素,包 括:before和:aft

Java併發程式設計:CallableFutureFutureTask 獲取返回值

     在前面的文章中我們講述了建立執行緒的2種方式,一種是直接繼承Thread,另外一種就是實現Runnable介面。   這2種方式都有一個缺陷就是:在執行完任務之後無法獲取執行結果。   如果需要獲取執行結果,就必須通過共享變數或者使用執行緒通訊的方式來達到效果,這樣使用起來就比較麻煩。  

JavaScriptJavaPHP獲取前一個訪問頁面的URL地址

要獲取前一個訪問頁面的URL地址前後端語言都可以實現。 PHP          的是     $_SERVER['HTTP_REFERER'] JavaScript的是      document.referrer Java          則是     reque

js中建立新增刪除移動複製查詢()節點

1)建立新節點createDocumentFragment() //建立一個DOM片段createElement_x() //建立一個具體的元素createTextNode() //建立一個文字節點2)新增、移除、替換、插入appendChild() //新增removeC

PHP根據身份證號碼驗證獲取星座生肖性別函式

首先介紹一下身份證含義 新的18位身份證號碼各位的含義: 1-2位省、自治區、直轄市程式碼; 3-4位地級市、盟、自治州程式碼; 5-6位縣、縣級市、區程式碼; 7-14位出生年月日,比如19670401代表1967年4月1日; 15-17位為順序號,其中17位男為單數,

unity transform元件position,rotation的世界本地獲取方法

 (本人水平有限,錯了還請指出,感激不盡)       在unity的檢視面板中,我們從transform元件中看到的position和rotation都是基於父物體的本地座標和角度。 世界位置和角度在指令碼中的獲取辦法: (注意:transform.eulerAngle

Chrome禁用NPAPI插件(包含 SilverlightJava Unity)

公眾 現在 app 包含 體驗 webgl 禁止 帶來 ext 過去,很多插件都是使用一種稱為NPAPI 的舊系統開發的。現在,僅僅有少量站點在使用NPAPI 插件,由於這些插件有時會給站點帶來安全風險。 為了讓用戶獲得更安全、更高速且更穩定的 Chrom

jquery中獲取相鄰元素相關的命令:next()prev()siblings()

cnblogs lin Language javascrip prev round blog scrip color jquery裏我們要獲取某個元素的相鄰元素時,可以用到的命令有三個: next():用來獲取下一個同輩元素。 prev():用來獲取上一個同輩元素。 sib

Git查看刪除重命名遠程分支tag

arr 錯誤 archive 1.7 rac 人在 post upd local 本文鏈接:http://zengrong.net/post/1746.htm 這篇文章記錄我在使用git的過程中碰到遠程分支和tag的相關內容,提綱: 查看遠程分支 刪除遠程分支和tag

根據馬甲應用商店統計每天的註冊量,要求可以根據選擇馬甲app,馬甲appstroreuser_login不同表問題

統計 eat create group ror 一次 instr 發現 用戶登錄 這個馬甲屬於一個表,appStore另一張表,用戶登錄表,主要操作的就是這三個表。 我這裏的馬甲和app的id都與用戶登錄表中的channel對應,在channel存放的是majiaId +

扒一扒.net.net frameworkmonoUnity

加載 blank unit 包括 基礎 開發者 data- features lan zhaichao 標簽: .net.net frameworkc#monounity 2017-04-23 14:39 425人閱讀 評論(0) 收藏 舉報 版權聲明:本文為博主

JQuery 中this$(this)獲取對象操作DOM對象的元素屬性

class 獲取對象 clas details 對象 query 操作 active html $(‘.button‘).click(function () { var active = $(‘.buttons-tab a‘).children(‘input‘).at

381 Insert Delete GetRandom O(1) - Duplicates allowed O(1) 時間插入刪除獲取隨機元素 - 允許重復

etc size 初始 結構 randomize lse 相同 HERE 時間復雜度 設計一個支持在平均 時間復雜度 O(1) 下, 執行以下操作的數據結構。註意: 允許出現重復元素。 insert(val):向集合中插入元素 val。 remove(val):

JS獲取客戶端IP地址MAC主機名的7個方法彙總

這篇文章主要介紹了JS獲取客戶端IP地址、MAC和主機名的7個方法彙總,JS本身是不支援獲取IP地址等資訊的,本文通過其它方法實現,需要的朋友可以參考下 今天在搞JS(javascript)獲取客戶端IP的小程式,上網搜了下,好多在現在的系統和瀏覽器中的都無效,很無奈,在C

Leetcode 380. 常數時間插入刪除獲取隨機元素

限定 速度 private hash list true keymap 插入 new 題目描述: 設計一個支持在平均 時間復雜度 O(1) 下,執行以下操作的數據結構。 insert(val):當元素 val 不存在時,向集合中插入該項。 remove(val):元素

JsJquery獲取節點屬性等

1、 獲取和設定屬性 Jquery: $("#testid").attr("value"); //獲取屬性為value的值 $("#testid").attr("value","1"); //設定屬性為value的值 $("#testid").removeAttr("val

Unity 模型在移動端進行移動旋轉放大(縮小)

using System.Collections; using System.Collections.Generic; using UnityEngine; public class RotateControl : MonoBehaviour { //float xSpeed = 100f