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小白如有错误,请指正,谢谢。