Unity3D中,GameObject和Tramsform类是最基础也是比较重要的类,GameObject类主要掌管各个游戏对象,每一个游戏对象都是一个GameObject,也可以说GameObject就是游戏对象。Tramsform类主要控制对象的位置,大小等属性。下面介绍几个小的案例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//GameObject类
public class text1 : MonoBehaviour
{
// Start is called before the first frame update
public GameObject Cube;
public GameObject Sphere;
public GameObject Capsule;
void Start()
{
Cube = GameObject.Find("Cube");//通过名称查找游戏对象对象
Sphere = GameObject.Find("/Cube/Sphere");
Capsule = GameObject.Find("/Cube/Sphere/Capsule");
gameObjects = GameObject.FindGameObjectsWithTag("Untagged");
Cube.AddComponent<Rigidbody>();
Cube.AddComponent<Collider>();//赋予对象各种组件,刚体,碰撞等。
Capsule.AddComponent<Rigidbody>();
Capsule.AddComponent<Collider>();
}
// Update is called once per frame
void Update()
{
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Tramsform类
public class text1 : MonoBehaviour
{
// Start is called before the first frame update
public Transform Cube;
public Transform player;
void Start()
{
Debug.Log(transform.localPosition);//相对于父物体的坐标
Debug.Log(transform.localScale);//缩放
Debug.Log(transform.eulerAngles);//欧拉角
Debug.Log(transform.right);//x坐标
Debug.Log(transform.up);//y坐标
Debug.Log(transform.forward);//z坐标
}
// Update is called once per frame
void Update()
{
//transform.Translate(Vector3.forward * Time.deltaTime * 10);//向前移动物体
//transform.Translate(Vector3.forward, Space.Self);//向前移动 相对于自身轴
//transform.Translate(transform.forward,Space.World);//向前移动 相对于世界坐标
//transform.Translate(transform.forward,Space.Self);//向前移动被 相对于自身轴
transform.position +=new Vector3(1,1,1); //物体当前位置加上向前移动的位置
Debug.Log(this.transform.position);
}
}