🏆 个人愚见,没事写写笔记
🏆《博客内容》:Unity3D开发内容
🏆🎉欢迎 👍点赞✍评论⭐收藏
🔎目标:GameObject成员变量
☀️实现:
注:注释的代码都可以打开测试一下。
public class Learn4 : MonoBehaviour
{
private void Start()
{
#region GameObject中的成员变量
//名字
print(this.gameObject.name);
this.gameObject.name = "Test04";
//是否激活
print(this.gameObject.activeSelf);
//是否静态
print(this.gameObject.isStatic);
//层级
print(this.gameObject.layer);
//标签
print(this.gameObject.tag);
//transform
print(this.gameObject.transform.position);
#endregion
#region GameObject中的静态方法
//创建内置几何体
GameObject createCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
createCube.name = "创建的cube";
//查找对象相关
//无法找到失活状态的对象
//同名对象没办法准确找到物体
//1.查找单个对象
//根据名字查找
GameObject findNameGameObject = GameObject.Find("Test04");//查找效率比较低下,因为会在场景中所有对象去查找
if (findNameGameObject != null)
{
print("找到物体");
}
else
{
print("未找到物体");
}
//根据标签查找
GameObject findTagGameObject = GameObject.FindWithTag("Player");
//GameObject findTagGameObject = GameObject.FindGameObjectWithTag("Player");//同理
if (findTagGameObject != null)
{
print("找到物体");
}
else
{
print("未找到物体");
}
//2.查找多个对象
//根据标签查找
GameObject[] findTagGameObjectArray = GameObject.FindGameObjectsWithTag("Player");
print(findTagGameObjectArray.Length);
//3.一般不用效率极其低下
Learn4 l4 = GameObject.FindObjectOfType<Learn4>();
print(l4.gameObject.name);
//实例化对象(克隆对象)的方法
//GameObject.Instantiate();
//删除对象的方法
//Destroy();
//注意:Destroy方法 不会马上移除对象,只是给这个对象添加了一个移除标识,
//一般情况下下一帧时把这个对象从内存中移除
//异步删除,降低卡顿
//立即删除
//DestroyImmediate();
//跳转场景不移除
//DontDestroyOnLoad();
#endregion
#region GameObject中的成员方法
//创建空物体
GameObject obj1 = new GameObject("创建空物体", typeof(BoxCollider));
//为对象添加脚本
//obj1.AddComponent(typeof(MeshRenderer));
obj1.AddComponent<MeshRenderer>();
//得到脚本
obj1.GetComponent<MeshRenderer>();
//标签比较
bool isCom = obj1.CompareTag("Player");
//同理:bool isCom = obj1.tag == "Player";
//设置激活失活(true/false)
//obj1.SetActive(false);
//消息效率低
//广播
//this.gameObject.SendMessage("Learn4FunTest");
//this.gameObject.BroadcastMessage("Learn4FunTest");
//this.gameObject.SendMessageUpwards("Learn4FunTest");
#endregion
}
private void Learn4FunTest()
{
print("Learn4FunTest");
}