当前位置:   article > 正文

Unity之GameObject类_unity gamobject.find

unity gamobject.find

GameObject.Find:

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

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()
    {
        
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

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()
    {
        
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

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

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号