组件都是在某个游戏物体身上挂载的,因此可以通过游戏物体查找获取后使用
首先创建一个游戏物体GameObject01,然后添加一个脚本组件Component1
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Component1 : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Component1 com1 = gameObject.GetComponent<Component1>();
Debug.Log(com1);
}
// Update is called once per frame
void Update()
{
}
}
gameObject直接就是挂载该组件的游戏物体
如果是其他游戏物体的组件,我们可以先去找到改游戏物体
GameObject gameobject1 = GameObject.Find("DogPBR");
Component2 com2 = gameobject1.GetComponent<Component2>();
Debug.Log(com2);