核心组件

在Unity中,核心组件之间的关系和访问方式可以这样梳理:

  1. 基础组件关系图

GameObject (游戏对象)

├── Transform (变换组件) - 控制位置/旋转/缩放
├── Collider2D (碰撞体) - 物理交互基础
├── Rigidbody2D (刚体) - 物理模拟
└── MonoBehaviour (脚本) - 自定义逻辑

  1. 关键组件访问方式

(1) Transform

1
2
3
4
5
6
7
8
9
10
11
// 获取自身Transform
Transform selfTF = GetComponent<Transform>();

// 访问属性
Vector3 position = selfTF.position;
Quaternion rotation = selfTF.rotation;
Vector3 scale = selfTF.localScale;

// 修改属性
selfTF.position = new Vector3(1, 0, 0);
selfTF.Rotate(0, 90, 0);

(2) GameObject

1
2
3
4
5
6
7
8
// 获取当前对象
GameObject selfGO = gameObject;

// 通过名称查找子对象
Transform childTF = transform.Find("foot");

// 激活状态控制
gameObject.SetActive(false);

(3) Collider2D

1
2
3
4
5
6
7
8
9
10
11
Apply
// 获取碰撞体
Collider2D collider = GetComponent<Collider2D>();

// 启用/禁用
collider.enabled = false;

// 触发检测 (需挂载脚本)
void OnTriggerEnter2D(Collider2D other) {
if(other.CompareTag("Player")) {...}
}
  1. 组件间相互调用
    方式1:直接获取组件
1
2
3
4
5
6
7
Apply
// 获取同一物体上的组件
Rigidbody2D rb = GetComponent<Rigidbody2D>();

// 获取其他物体的组件(需先获取GameObject)
GameObject player = GameObject.Find("Player");
charactor_move_v script = player.GetComponent<charactor_move_v>();

方式2:通过公开引用

1
2
3
4
5
6
7
Apply
// 在Inspector面板拖拽赋值
public Transform targetTF;

void Start() {
Vector3 pos = targetTF.position;
}

方式3:父子层级访问

1
2
3
4
5
// 获取父对象
Transform parent = transform.parent;

// 获取子对象
Transform child = transform.GetChild(0);
  1. 你的代码中的典型调用案例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Apply
// 获取Rigidbody2D组件(物理模拟)
private Rigidbody2D rb;
void Start() {
rb = GetComponent<Rigidbody2D>();
}

// 通过标签查找对象
if(other.CompareTag("FollowBox")) {...}

// 访问其他脚本属性
float power = currentPlayer.GetComponent<charactor_move_v>().kick_power;

// 修改碰撞体状态
playerCollider.enabled = false;
  1. 最佳实践建议
    缓存引用:在Start()中获取常用组件,避免重复调用GetComponent
    分层查找:使用transform.Find(“路径/子对象”)按路径查找
    空值检查:对GetComponent结果做null检查
    性能优化:避免在Update中频繁查找对象
    这种组件系统构成了Unity的”组合优于继承”架构,通过灵活的组合实现复杂游戏逻辑。

多版本.NET切换

dotnet –list-sdks 查看已安装的.NET版本