核心组件
在Unity中,核心组件之间的关系和访问方式可以这样梳理:
- 基础组件关系图
GameObject (游戏对象)
│
├── Transform (变换组件) - 控制位置/旋转/缩放
├── Collider2D (碰撞体) - 物理交互基础
├── Rigidbody2D (刚体) - 物理模拟
└── MonoBehaviour (脚本) - 自定义逻辑
- 关键组件访问方式
(1) Transform
1 2 3 4 5 6 7 8 9 10 11
| 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 2 3 4 5 6 7
| Apply
Rigidbody2D rb = GetComponent<Rigidbody2D>();
GameObject player = GameObject.Find("Player"); charactor_move_v script = player.GetComponent<charactor_move_v>();
|
方式2:通过公开引用
1 2 3 4 5 6 7
| Apply
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| Apply
private Rigidbody2D rb; void Start() { rb = GetComponent<Rigidbody2D>(); }
if(other.CompareTag("FollowBox")) {...}
float power = currentPlayer.GetComponent<charactor_move_v>().kick_power;
playerCollider.enabled = false;
|
- 最佳实践建议
缓存引用:在Start()中获取常用组件,避免重复调用GetComponent
分层查找:使用transform.Find(“路径/子对象”)按路径查找
空值检查:对GetComponent结果做null检查
性能优化:避免在Update中频繁查找对象
这种组件系统构成了Unity的”组合优于继承”架构,通过灵活的组合实现复杂游戏逻辑。
多版本.NET切换
dotnet –list-sdks 查看已安装的.NET版本