拿到物体的某些数据
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class game : MonoBehaviour
{// Start is called before the first frame updatevoid Start(){//拿到当前脚本所挂载的游戏物体//GameObject go = this.gameObject;//可以直接用gameObject拿到Debug.Log(gameObject.name);//名称Debug.Log(gameObject.tag);//标签 Debug.Log(gameObject.layer);//图层}// Update is called once per framevoid Update(){}
}
在a物体中操作b物体属性
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class game : MonoBehaviour
{// Start is called before the first frame updatepublic GameObject Cube;void Start(){//拿到当前脚本所挂载的游戏物体//GameObject go = this.gameObject;//可以直接用gameObject拿到Debug.Log(gameObject.name);//名称Debug.Log(gameObject.tag);//标签 Debug.Log(gameObject.layer);//图层 Debug.Log(Cube.name);//名称//当前真正的激活状态,当父物体是非激活状态的时候,他是激活状态显示falseDebug.Log(Cube.activelnHierarchy);//当前自身激活状态Debug.Log(Cube.activeself);}// Update is called once per framevoid Update(){}
}
在物体类中获取组件
获取Transform组件
//Transform trans = this.transform;
Debug.Log(transform.position);//Transform组件的位置
获取其他组件
//类型 变量名 = GetComponent<类型>
BoxCollider bc = GetComponent<BoxCcflider>();
获取当前物体的子物体身上的某个组件
GetComponentlnChildren<CapsuleCollider>(bc)
获取当前物体的父物体身上的某个组件
GetComponentlnParent<BoxCollider>();
添加一个组件
//给自己添加
gameObject.Addcomponent<AudioSource>();
//给其他物体添加Cube.Addcomponent<AudioSource>();
其他获取物体的方法(有很多,下面介绍两种方式)
1、通过名称获取
//通过游戏物体的名称来获取游戏物体 GameObject test = GameObject.Find("名称");
GameObject test = GameObject.Find("Test");
Debug.Log(test.name);
2、通过标签获取
//通过游戏物体的名称来获取游戏物体 GameObject test = GameObject.Find("名称");
GameObject test = GameObject.FindWithTag("Test");
Debug.Log(test.name);
通过代码生成一个物体
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class game : MonoBehaviour
{// Start is called before the first frame updatepublic GameObject Cube;public GameObject prefab;void Start(){//通过预设体实例化物体Instantiate(prefab);//通过物体实例化物体Instantiate(Cube);//可以指定父物体Instantiate(prefab,transform); //可以指定位置000的位置,不旋转GameObject go = Instantiate(prefab,Vector3.zero,Quaternion.identity);//销毁Destroty(go)}// Update is called once per framevoid Update(){}
}