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

如何解决非int值条件判断时出现的CS0472警告?

解决Unity C#中的CS0472警告问题

问题场景

我编写了如下Unity C#代码用于判断井字棋获胜条件:点击GameObject时,其Sprite会被添加到默认包含null值的BusyPlaces数组中。但在if条件判断时出现CS0472警告,提示“bool不能为null”,实际我是想判断Sprite值是否满足获胜条件。

private static Sprite[] BusyPlaces = new Sprite[9];

private int[,] WAYS_TO_WIN = new int[8, 3]
{
    {0, 1, 2},
    {3, 4, 5},
    {6, 7, 8},
    {0, 3, 6},
    {1, 4, 7},
    {2, 5, 8},
    {0, 4, 8},
    {2, 4, 6}
};

private void Winner() 
{
    int[] arr = new int[3];

    for (int i = 0; i < WAYS_TO_WIN.GetLength(0); i++)
    {
        for (int j = 0; j < WAYS_TO_WIN.GetLength(1); j++)
        {
            arr[j] = WAYS_TO_WIN[i, j];
        }

        
        if (BusyPlaces[arr[0]] == BusyPlaces[arr[1]] == BusyPlaces[arr[2]] != null)
        {
            announce_winner.text = "Winner";
        }
    }
}

问题原因

当前if条件的写法存在逻辑错误:

  • BusyPlaces[arr[0]] == BusyPlaces[arr[1]]会返回一个bool值(true或false)
  • 接着用这个bool值与BusyPlaces[arr[2]]比较,属于不同类型的非法对比
  • 最后再将对比结果与!= null关联,而bool是值类型,无法与null比较,这就触发了CS0472警告

修复方案

拆分条件逻辑,先确保三个位置的Sprite都不为null,再判断三者是否相等:

private static Sprite[] BusyPlaces = new Sprite[9];

private int[,] WAYS_TO_WIN = new int[8, 3]
{
    {0, 1, 2},
    {3, 4, 5},
    {6, 7, 8},
    {0, 3, 6},
    {1, 4, 7},
    {2, 5, 8},
    {0, 4, 8},
    {2, 4, 6}
};

private void Winner() 
{
    int[] arr = new int[3];

    for (int i = 0; i < WAYS_TO_WIN.GetLength(0); i++)
    {
        for (int j = 0; j < WAYS_TO_WIN.GetLength(1); j++)
        {
            arr[j] = WAYS_TO_WIN[i, j];
        }

        Sprite s0 = BusyPlaces[arr[0]];
        Sprite s1 = BusyPlaces[arr[1]];
        Sprite s2 = BusyPlaces[arr[2]];
        
        // 先校验非null,再判断三者相等
        if (s0 != null && s1 != null && s2 != null && s0 == s1 && s1 == s2)
        {
            announce_winner.text = "Winner";
        }
    }
}

修改后既避免了类型不匹配的问题,也保证了逻辑正确性:只有当三个位置都存在Sprite,且三个Sprite完全相同时,才判定为获胜。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 01:10:11