GetComponent是Unity3D开发中不可或缺的一个方法,它允许开发者轻松地访问和操作GameObject上的组件。然而,为了保持应用的性能,开发者应该谨慎使用GetComponent,并考虑在可能的情况下缓存组件引用。通过理解GetComponent的工作原理和注意事项,开发者可以更有效地利用这一强大的工具来构建他们的游戏和应用程序。 更多教学视频 Un...
public Component GetComponent(Type type); public T GetComponent<T>(); GetComponent(Type type):这是一个泛型方法,但你需要显式传递一个Type对象作为参数。这通常不是最常用的形式,因为GetComponent<T>()提供了更简洁的语法。 GetComponent<T>():这是最常用的形式,其中T是你想要获取的组件的类型。这种方法利用...
编写脚本时反复计算一个值是常见的问题,特别是在使用一些成本比较高的方法时,比如GetComponent、GameObject.Find()等。 void Update() { TakeDamage(); } void TakeDamage() { Rigidbody rig = GetComponent<Rigidbody>(); Collider collider = GetComponent<Collider>(); Animator animator = GetComponent<Animator>...
public Component GetComponent (string type); 描述 如果游戏对象附加了名为 type 的组件,则将其返回,否则返回 null。 出于性能原因,最好使用具有 Type 而不是字符串的 GetComponent。但有时可能无法访问该类型,例如在尝试从 Javascript 访问 C# 脚本时。在这种情况下,可以仅根据名称而不是类型访问该组件。示例:...
Unity3d--GetComponent的使用方法 1usingUnityEngine;2usingSystem.Collections;34publicclassTest : MonoBehaviour {56privateQuaternion[] quaters;7privateColor[] colors;8privateMaterial mr;910voidAwake(){11quaters =newQuaternion[7];12colors =newColor[7];13}1415voidStart () {16inti =0;17while(i<quate...
GetComponent<ParentMenu>().Init(childRect, cntArr[i]); int j = i; //父物体上面的button绑定事件 parentArr[i].GetComponent<Button>().onClick.AddListener(() => { OnButtonClick(j); }); } } void OnButtonClick(int i) { //如果iscanclick为false则return 因为已经点击过了 不能再点击了 ...
using UnityEngine;using System.Collections;// 控制坦克移动publicclassTank_Move:MonoBehaviour{privateRigidbody r;privatefloat speed=5f;privatefloat angularSpeed=10f;// 判断当前坦克publicbool isCurrentTank=true;publicAudioClip idle;publicAudioClip Run;publicAudioSource tankSound;voidStart(){r=GetComponent<...
总结了三种使用GetComponentsInChildren时的情况,使用需谨慎。 一、能获取到自己的情况 Transform[] trans = GetComponentsInChildren<Transform>(); 因为root对象以及其6个子对象都有Transform组件,所以获取到的size是7,包含了root自身节点。 二、不能获取到自身的情况 ...
动画回调函数是指动画在开始时、执行中、结束时回调的函数,主要有:OnStateEnter、OnStateUpdate、OnStateExit、OnStateMove、OnStateIK。 1)动画状态判断 Animatoranimator=GetComponent<Animator>();intlayerIndex=0;// 动画层号// 判断当前正在运行的动画是否是指定的动画animator.GetCurrentAnimatorStateInfo(layerIndex...
Rigidbody rig = GetComponent<Rigidbody>(); 2)刚体组件面板属性 Mass:物体的质量(默认以千克为单位) Drag:物体受到的空气阻力大小 Angular Drag:物体旋转时,受到的旋转阻力大小转 Use Gravity:如果启用,物体将受到重力的影响 Is Kinematic:如果启用,物体将不会由物理引擎驱动,只能由其 Transform 组件操作 ...