Unity中获取游戏对象的组件

本文转载自Unity 得到游戏组件的常用的两种方法

常用的获取游戏对象组件的方法

  1. 获取当前挂载游戏对象的组件

index = this.GetComponent<******>();
// ******为目标组件

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Player1 : MonoBehaviour {
 
	private MeshRenderer meshRender;  //声明需要得到的组件
	public Material otherMaterial;  //声明一个材质,在Unity界面进行赋值
 
	void Start () {
		meshRender = this.GetComponent<MeshRenderer> ();  //把该物体的组件赋值到声明的变量中
	}
	void Update () {
		if (Input.GetKeyDown (KeyCode.Z)) {  //如果按下了Z键
			meshRender.material = otherMaterial;   //更改材质
		}
	}
}
  1. 获取其他游戏对象组件

index = other.GetComponent<******>();
// ******为目标组件

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Player2 : MonoBehaviour {
 
	public GameObject player1;  //声明需要得到的游戏物体,在Unity界面进行赋值
	public Material otherMaterial;  //声明一个需要更换的材质,在Unity界面进行赋值
	private MeshRenderer meshrenderer;  //声明需要得到的组件
 
	void Start () {
		meshrenderer = player1.GetComponent<MeshRenderer> ();  //得到Player1的MeshRenderer组件
	}
	void Update () {
		if (Input.GetKeyDown (KeyCode.Q)) {   //按下Q键
			meshrenderer.material = otherMaterial;  //就可以更换材质贴图
		}
	}
}
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值