You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中如何检测碰撞的GameObject并实现不同鸟类的差异化计分?

搞定Unity击中不同鸟类加不同分的问题

嘿,兄弟,我来帮你解决这个问题!先给你捋清楚两个关键点:为啥会报错,还有更省心的实现方法。

首先,你报错的原因

你写的if(other.gameObject = bird1)这里犯了个小错误:用了赋值运算符=,而不是比较运算符==。=是把bird1的值塞给other.gameObject,但gameObject是只读属性(不能被赋值),所以Unity就报错啦。

把所有的=改成==,这个错误就会消失:

void OnTriggerEnter(Collider other) {
    if(other.gameObject == bird1) { // 这里改成==
        Destroy(other.gameObject);
        player.GetComponent<PlayerController>().score += 1;
    } else if(other.gameObject == bird2) { // 这里也改成==
        Destroy(other.gameObject);
        player.GetComponent<PlayerController>().score += 2;
    } else if(other.gameObject == bird3) { // 还有这里
        Destroy(other.gameObject);
        player.GetComponent<PlayerController>().score += 3;
    }
}

不过这个方法虽然能跑,但有个问题:以后要是加第4只、第5只鸟,你得一直加else if,代码会越来越乱。下面给你两个更灵活的办法,新手也能轻松上手。


方法1:用「标签(Tag)」区分鸟类

这个方法不用提前找鸟的GameObject,直接靠标签判断:

  1. 先给每只鸟设置不同的标签:
    • 选中Bird1,在Inspector面板的Tag下拉框里选「Add Tag」,新建标签比如Bird1
    • 同理给Bird2设Bird2,Bird3设Bird3
  2. 修改你的碰撞代码:
void OnTriggerEnter(Collider other) {
    // 先拿到玩家的分数组件,避免重复调用GetComponent,省点性能
    var playerScore = player.GetComponent<PlayerController>();
    
    // 用CompareTag比直接写other.tag == "Bird1"更高效,还不容易写错
    if (other.CompareTag("Bird1")) {
        Destroy(other.gameObject);
        playerScore.score += 1;
    } else if (other.CompareTag("Bird2")) {
        Destroy(other.gameObject);
        playerScore.score += 2;
    } else if (other.CompareTag("Bird3")) {
        Destroy(other.gameObject);
        playerScore.score += 3;
    }
}

方法2:给鸟类加「自定义分数脚本」(最推荐!)

这个方法最灵活,以后加新鸟完全不用改碰撞代码,只需要给新鸟拖个脚本设分数就行:

  1. 新建一个C#脚本,命名为BirdScore,代码如下:
using UnityEngine;

public class BirdScore : MonoBehaviour
{
    // 这个变量可以在Inspector面板里直接改,给每只鸟设对应的分数
    public int scoreValue; 
}
  1. 把这个脚本分别拖给Bird1、Bird2、Bird3:
    • 选中Bird1,在Inspector里找到BirdScore组件,把scoreValue设为1
    • Bird2设为2,Bird3设为3
  2. 修改你的碰撞代码:
void OnTriggerEnter(Collider other) {
    // 检查碰撞的物体有没有BirdScore组件
    BirdScore birdScore = other.GetComponent<BirdScore>();
    
    // 如果有,说明是我们要的鸟类,就加分销毁
    if (birdScore != null) {
        Destroy(other.gameObject);
        player.GetComponent<PlayerController>().score += birdScore.scoreValue;
    }
}

以后你加第4只鸟,只要拖这个脚本,把scoreValue设成你想要的数(比如5),代码完全不用改,是不是超级省心?


内容的提问来源于stack exchange,提问作者Business Cactus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 18:32:40