Unity几种查找物体的方法

Unity版本为5.3.2

在脚本中查找游戏物体是非常常见的,这里列一些查找方法


首先是Transform下面的

using UnityEngine;
using System.Collections;

public class Communicate : MonoBehaviour {

    // Use this for initialization
    void Start () {
        Transform name1 =  transform.Find ("GameObject/name");//使用transform.find只能查询自身下一级的子物体,且子物体是否激活都能查到,若查询多级的子物体则加'/',hierarchy的路径
        Transform name2 = transform.FindChild("name");//这个跟transform.find一样
        print(name1);
        print(name2);
    }

    // Update is called once per frame
    void Update () {

    }
}

GameObject下面的

using UnityEngine;
using System.Collections;

public class Communicate : MonoBehaviour {

    // Use this for initialization
    void Start () {
        GameObject name1 = GameObject.Find("name");//能查询,hierarchy中所有的物体,但是必须是激活的
        GameObject name2 = GameObject.FindGameObjectWithTag("name");//根据tag查找物体,但是必须是激活的
        GameObject[] name3 = GameObject.FindGameObjectsWithTag("name");//根据tag查找同一tag的物体,但是必须是激活的
    }

    // Update is called once per frame
    void Update () {

    }
}

这里注意出于性能原因,建议不要每帧使用GameObject.Find(),而应在启动时将结果缓存到成员变量中,或使用GameObject.FindWithTag。


Object下面的

using UnityEngine;
using System.Collections;

public class Communicate : MonoBehaviour {

    // Use this for initialization
    void Start () {
        Transform name1 = FindObjectOfType(typeof(Transform))as Transform;//在hierarchy中查找有transform组件的物体,必须是激活的
        Transform[] name = FindObjectsOfType(typeof(Transform))as Transform[];//在hierarchy中查找有transform组件的物体,必须是激活的
    }

    // Update is called once per frame
    void Update () {

    }
}

这里需要注意一点,使用这个方法很慢


  • 5
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值