当前位置:网站首页>【Unity入门计划】GameObject类(1)-GetComponent方法
【Unity入门计划】GameObject类(1)-GetComponent方法
2022-08-07 12:20:00 【flashinggg】
官方文档
Component-GetComponent - Unity 脚本 API
格式
GameObject.GetComponent<Type>()
其中:
GameObject——当前游戏对象的变量名称
Type——组件名称,类型是string
用途
GetComponent是获取当前游戏对象组件的方法,可以通过直接调用它来访问游戏对象的组件和进行参数调整。
使用举例
1 获取组件
假设我们知道场景中有一个"Ruby"玩家游戏对象,“Ruby”挂了一个Type为Rigidbody 2D的刚体组件,就可以通过GetComponent方法来获取Ruby的刚体组件。

- 首先,获取到的Rigidbody2D组件需要被赋予给另一个变量,这个变量需要有跟Rigidbody2D具有相同类型,因此需要先定义一个Rigidbody2D类型的对象
using UnityEngine;
public class RubyController : MonoBehaviour
{
//声明一个刚体对象
Rigidbody2D rigidbody2D;
}- 下面就可以进行赋予了
using UnityEngine;
public class RubyController : MonoBehaviour
{
//声明一个刚体对象
Rigidbody2D rigidbody2D;
private void start(){
//游戏运行前,获取当前游戏对象的刚体组件
rigidbody2D = GetComponent<Rigidbody2D>();
}
}
2 定义组件属性
除了获取组件,还可以通过GetComponet来定义组件属性的值,比如:

//定义Mass为5
GetComponent<Rigidbody2D>.mass = 5;直接使用GetComponent()以提高性能
根据官方文档所述,可以将
rigidbody2D = GetComponent<Rigidbody2D>();
换成
rigidbody2D = GetComponent("Rigidbody2D");
以提高性能。
边栏推荐
- Construction of CCNA--GNS3 simulation environment and beautification and debugging of SecureCRT8.7 program console
- 备考:“十四五'发展规划和2035年远景目标
- PAT 刷题笔记
- 周末复盘,高手不卖产品只讲故事!
- The pit of copying code online
- 中国石油大学(北京)-《油藏工程》第二阶段在线作业
- [js] Calculate the distance from the child node to the parent node and scroll to the position
- 自定义类型:结构体,枚举,联合
- CISP-PTE实操练习之综合题讲解(win2008)
- UGUI series - realize progress bar effect (Unity3D)
猜你喜欢

由GEE生成逐月MODIS的NDVI影像

dll修复工具安装教程

How to find three and in an array of fixed value not repeating elements?Double pointer address leetcode 15. Three Numbers together

Altium Designer 19.1.18 - 创建一块和 Keep-Out Layer 形状一样的铜皮

若依集成just-auth实现第三方授权登录

Monthly MODIS NDVI images generated by GEE

odoo社区版审批流

ESP8266-Arduino编程实例-TM36温度传感器驱动

Custom types: structs, enums, unions

如何在一个数组中找到三个和为定值的不重复元素? 双指针解决 leetcode 15.三数之和
随机推荐
dynamic memory management
Interesting feature: the CHECK constraint
耗时 48 小时,小米工程师发明小米头箍,网友:变身孙悟空不是梦!
CCNA-Installing SecureCRT 8.7 with GNS3 Emulation
Detailed explanation of grid_sample function in frame insertion
FairMOT在线跟踪框架及代码学习记录
让天下没有难学的js之this到底是什么,怎么用,这里可能给你答案
目标检测工具箱MMDetection安装及使用示例
Unet training and deployment tests
什么是 Office Open XML 文件格式
[Learning] What are the packages introduced in the code?
xxl-job的使用及简述原理
1. MongoDB概览
China University of Petroleum (Beijing) - "Drilling Fluid Technology Principle" Phase II Online Operation
我说MySQL联合索引遵循最左前缀匹配原则,面试官让我回去等通知
Custom types: structs, enums, unions
【New in 2022】Efficient brush buckle in all directions | Reverse linked list
Flutter packaging
UGUI series - principle analysis (Unity3D)
基于Gin的Go语言项目网盘实战解读