程序设计基础
登录
< 返回教程列表

3.2 Transform 与 GameObject

知识介绍

Transform: 管理对象的位置、旋转、缩放,以及父子关系。

using UnityEngine;

public class TransformDemo : MonoBehaviour
{
    public Transform target;  // 可以在 Inspector 拖一个对象

    private void Start()
    {
        // --- 位置 Position(世界坐标)---
        Vector3 pos = transform.position;
        transform.position = new Vector3(1, 2, 3);

        // 局部坐标(相对父物体)
        transform.localPosition = Vector3.zero;

        // 平移(世界轴)
        transform.Translate(0, 0, 1);                        // z+1
        transform.Translate(Vector3.forward * 5 * Time.deltaTime);

        // --- 旋转 Rotation ---
        // Euler 角(方便写)
        transform.eulerAngles = new Vector3(0, 45, 0);      // y轴旋转45°
        // 四元数(内部表示)
        transform.rotation = Quaternion.Euler(0, 45, 0);

        // 逐帧旋转
        transform.Rotate(0, 90f * Time.deltaTime, 0);       // 每秒y轴转90°

        // 看向目标
        transform.LookAt(target);

        // --- 缩放 Scale ---
        transform.localScale = new Vector3(2, 2, 2);        // 放大2倍

        // --- 父子关系 ---
        transform.parent = target;                          // 设父物体
        int childCount = transform.childCount;              // 子物体数
        Transform child = transform.GetChild(0);            // 获取第0个子物体
    }
}

GameObject: 场景中的"物体"。

using UnityEngine;

public class GameObjectDemo : MonoBehaviour
{
    public GameObject prefab;      // 预制体(Inspector 拖入)

    private void Start()
    {
        // 创建内置物体
        GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        cube.name = "我的Cube";
        cube.transform.position = new Vector3(0, 1, 0);

        // 添加组件
        cube.AddComponent<Rigidbody>();
        // 获取组件
        Rigidbody rb = cube.GetComponent<Rigidbody>();
        rb.mass = 2;

        // 实例化预制体(克隆)
        GameObject go = Instantiate(prefab, new Vector3(3, 0, 0), Quaternion.identity);

        // 销毁
        Destroy(cube, 3f);  // 3秒后销毁
        Destroy(go);        // 立即销毁

        // 激活/禁用
        go.SetActive(false);   // 禁用(灰色)
        bool isAlive = go.activeSelf;

        // 按名字查找(慎用,慢)
        GameObject player = GameObject.Find("Player");
        // 按标签查找
        GameObject enemy = GameObject.FindWithTag("Enemy");
    }
}

常用 Vector3 常量:

Vector3.zero      // (0,0,0)
Vector3.one       // (1,1,1)
Vector3.forward   // (0,0,1)   Z轴正方向
Vector3.back      // (0,0,-1)
Vector3.up        // (0,1,0)   Y轴正
Vector3.down      // (0,-1,0)
Vector3.right     // (1,0,0)   X轴正
Vector3.left      // (-1,0,0)

例题

例题1: 让物体绕原点做圆周运动。

using UnityEngine;

public class CircleMove : MonoBehaviour
{
    public float radius = 3f;
    public float speed = 1f;
    private float _angle;

    private void Update()
    {
        _angle += speed * Time.deltaTime;
        float x = radius * Mathf.Cos(_angle);
        float z = radius * Mathf.Sin(_angle);
        transform.position = new Vector3(x, transform.position.y, z);
    }
}

例题2: 点一下鼠标左键生成一个随机颜色的 Cube。

using UnityEngine;

public class SpawnCube : MonoBehaviour
{
    private void Update()
    {
        // 鼠标左键按下
        if (Input.GetMouseButtonDown(0))
        {
            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            // 随机位置和颜色
            cube.transform.position = Random.insideUnitSphere * 3;
            cube.GetComponent<Renderer>().material.color = Random.ColorHSV();
            // 让它5秒后自动消失
            Destroy(cube, 5f);
        }
    }
}

练习题

  1. 写脚本让一个 Cube 在 X 轴上从 -5 到 5 来回运动(可以用 Mathf.PingPong)。

  2. 写脚本让物体一直绕 Y 轴自转,并且绕另一个"中心物体"公转转圈。

  3. 按空格生成一个带 Rigidbody 的 Sphere 从天上掉落(从 (0,10,0) 位置出生)。

  4. 写一个 LookAtTarget 脚本:public Transform target;,让当前物体每帧看向 target(比如让相机一直跟随看向角色)。

  5. 查找场景中所有 Tag 为 "Enemy" 的物体存到数组,按 1 键全部 SetActive(false),按 2 键全部恢复。