Unity之GameObject类

GameObject.Find:

    用于查找游戏对象,我们结合代码进行理解:
GameObject  cube;
cube=GameObject.Find("Cube");//在场景中找到Cube对象并把它赋给cube

GameObject.FindWithTag:

这个方法也是用来找游戏对象的,只不过是根据游戏对象的tag来匹配的。

GameObject.FindGameObjectWithTag

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

public class GameObjectGameOGjectWithTag : MonoBehaviour
{
    GameObject[] myObjects;
    // Start is called before the first frame update
    void Start()
    {
        myObjects = GameObject.FindGameObjectsWithTag("ObjectTag");
       foreach (GameObject o in myObjects)
        {
            Debug.Log(myObjects [1].name );//将Tag为ObjectTag的物体一一赋值给myObjects
        }
    }

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

GetCompoment<>()方法

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

public class GetCompoment : MonoBehaviour
{
    GameObject CubeObject;
    private MeshFilter meshFilter;//定义了一个MeshFilter类型的变量,用于保存相关的组件

    // Start is called before the first frame update
    void Start()
    {

        CubeObject = GameObject.Find("Cube");
        CubeObject.AddComponent<Rigidbody>();//给Cube加了一个刚体组件。
        meshFilter = CubeObject.GetComponent<MeshFilter>();//获得Cube的MeshFilter的组件
        Debug.Log(meshFilter.mesh);//打印出该组件的相关mesh材质。
    }

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

在代码块区域注释写的很详细了,就不再重复了。由于笔者是Unity小白如有错误,请指正,谢谢。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值