Unity3D数字孪生笔记(二)——Unity篇
一、常用API
1、Component
Component类提供了查找(在当前物体、后代、先辈)组件的功能。
- 常用属性
gameObject、transform、collider、renderer… - 常用方法
- GetComponent、GetComponentInChild、GetComponentInParent…
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Component类提供了查找(在当前物体、后代、先辈)组件的功能。
/// </summary>
public class ComponentDemo : MonoBehaviour
{
private void OnGUI()
{
if (GUILayout.Button("transform"))
{
this.transform.position = new Vector3(0, 0, 10);
}
if (GUILayout.Button("GetComponent"))
{
this.GetComponent<MeshRenderer>().material.color = Color.red;
}
if(GUILayout.Button("GetComponents"))
{
//获取当前物体所有组件
var allComponent = this.GetComponents<Component>();
foreach (var item in allComponent)
{
Debug.Log(item.GetType());
}
}
if(GUILayout.Button("GetComponentsInChildren"))
{
//获取后代物体的指定类型组件(从自身开始,从上往下)
var allComponent = this.GetComponentsInChildren<MeshRenderer>();
foreach (var item in allComponent)
{
item.material.color = Color.red;
}
}
if (GUILayout.Button("GetComponentsInParent"))
{
//获取先辈物体的指定类型组件(从自身开始,从下往上)
var allComponent = this.GetComponentsInParent<MeshRenderer>();
foreach (var item in allComponent)
{
item.material.color = Color.red;
}
}
}
}
2、Transform
Transform类 提供了 查找(父、根、子(索引、名称))变换组件、改变位置、角度、大小功能。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Transform类 提供了 查找(父、根、子(索引、名称))变换组件、改变位置、角度、大小功能
/// </summary>
public class TransformDemo : MonoBehaviour
{
//***********查找变换组件****************//
public Transform tf;
private void OnGUI()
{
if(GUILayout.Button("foreach--transform"))
{
foreach (Transform child in this.transform)
{
//child为 每个子物体的变换组件
print(child.name);
}
}
if(GUILayout