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

Azure Spatial Anchors Unity教程代码报错:distance变量作用域问题

教程代码问题分析及修复方案

这段教程代码的核心问题是变量作用域冲突,搭配解构赋值的类型推断问题,具体细节如下:

1. 首次报错的根源

外层通过var (distance, closestObject)的解构语法声明了distance变量,而Lambda表达式内部又用float distance声明了同名变量。C#不允许内层局部作用域声明与外层局部作用域同名的变量,因此触发报错:

'distance' cannot be declared in this scope because that name is used in an enclosing local scope

2. 修改后新报错的原因

当你去掉内层的float关键字后,编译器会默认你要引用外层的distance变量,但外层的distance是在Aggregate方法执行完成后才完成解构赋值的,Lambda表达式执行时该变量尚未声明,因此触发Cannot use local variable 'distance' before it is declared;同时,解构赋值的var需要编译器能推断出变量类型,但Lambda内部的逻辑无法反向推导解构变量的类型,进而触发Cannot infer the type of implicitly-typed deconstruction variable 'distance'。


修复方案一:修改内层变量名避免冲突

把Lambda里的distance变量改成其他名称,比如currentDistance,彻底规避作用域冲突,同时让编译器能正常推断解构变量的类型:

private bool IsAnchorNearby(Vector3 position, out GameObject anchorGameObject)
{
    anchorGameObject = null;

    if (_foundOrCreatedAnchorGameObjects.Count <= 0)
    {
        return false;
    }

    //Iterate over existing anchor gameobjects to find the nearest
    var (distance, closestObject) = _foundOrCreatedAnchorGameObjects.Aggregate(
        new Tuple<float, GameObject>(Mathf.Infinity, null),
        (minPair, gameobject) =>
        {
            Vector3 gameObjectPosition = gameobject.transform.position;
            // 修改变量名,避免与外层解构的distance冲突
            float currentDistance = (position - gameObjectPosition).magnitude;
            return currentDistance < minPair.Item1 ? new Tuple<float, GameObject>(currentDistance, gameobject) : minPair;
        });

    if (distance <= 0.15f)
    {
        //Found an anchor within 15cm
        anchorGameObject = closestObject;
        return true;
    }
    else
    {
        return false;
    }
}

修复方案二:放弃解构赋值,直接使用Tuple变量

如果觉得解构语法容易引发作用域问题,也可以直接操作Tuple对象,彻底绕开解构相关的类型推断问题:

private bool IsAnchorNearby(Vector3 position, out GameObject anchorGameObject)
{
    anchorGameObject = null;

    if (_foundOrCreatedAnchorGameObjects.Count <= 0)
    {
        return false;
    }

    //Iterate over existing anchor gameobjects to find the nearest
    var closestPair = _foundOrCreatedAnchorGameObjects.Aggregate(
        new Tuple<float, GameObject>(Mathf.Infinity, null),
        (minPair, gameobject) =>
        {
            Vector3 gameObjectPosition = gameobject.transform.position;
            float distance = (position - gameObjectPosition).magnitude;
            return distance < minPair.Item1 ? new Tuple<float, GameObject>(distance, gameobject) : minPair;
        });

    if (closestPair.Item1 <= 0.15f)
    {
        //Found an anchor within 15cm
        anchorGameObject = closestPair.Item2;
        return true;
    }
    else
    {
        return false;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:15:43