Почему эта ссылка на локальный интерфейс выходит за рамки? - PullRequest
0 голосов
/ 15 марта 2020

Работаю над проектом Unity, и я кеширую ссылку на GameObject через его реализованный интерфейс в начале моей сопрограммы. По какой-то причине эта переменная «выходит за рамки», когда я ее отлаживаю. Это приводит к тому, что любая переменная, которая ссылается на нее (как, например, логическое значение ниже), также выходит из области видимости. Я пробовал несколько исправлений, начиная с обновления VS2019 и заканчивая обеспечением запуска всех проектов при подключении к Unity для отладки. Я испробовал все исправления, относящиеся к моей проблеме, предложенные здесь:

Отладка Visual Studio 2015: не удается развернуть локальные переменные?

Ничто из того, что я делаю, не позволяет мне изучить эту переменную или все, что с ней связано. Он не отображается в окне Locals. Я не уверен, что мне здесь не хватает, но отладка этого кода была настоящей болью. Любая помощь будет оценена!

РЕДАКТИРОВАТЬ: Предоставленный пример кода:

private IEnumerator TranslateTouchableNew(Touchable translator, OffsetTransform destination)
{
    bool hasArrived = false;

    ITouchTranslationProfile profile = translator.TranslationProfile;
    bool hasProfile = (profile != null);

    //Translator position vars
    Vector3 positionBeforeYArcOffset = translator.transform.position;
    Vector3 newPosition;
    Vector3 normalizedHeading = Vector3.zero;

    //Destination & Distance
    Vector3 destinationWithOffsets = CalculateDestinationWithOffsets();
    float startingDistance = (destinationWithOffsets - positionBeforeYArcOffset).magnitude; //Length between the translator transform and the final destinatin vector after considering receptacle offset and translator mesh offset
    float currentDistance = startingDistance;
    float distanceCoveredPercent;

    //Applying profile values, if they exist; otherwise use default values for speed and arc
    AnimationCurve yArc = hasProfile && profile.YArcOverride != null ? profile.YArcOverride : standardYArcOffset;
    float yArcProximityFactor = yArcByProximityFactor.Evaluate(startingDistance);
    float speed = hasProfile ? metersPerSecond * profile.SpeedScalePercent : metersPerSecond;

    while (!hasArrived)
    {
        //Skip standard translator logic for custom implementation on the translator
        if (hasProfile && profile.UseCustomTranslation) hasArrived = profile.CustomTranslateUntilArrived(destination);
        else
        {
            //Calculate the final destination. Because the destination is transform based (it can move), this needs to be done every frame.
            destinationWithOffsets = CalculateDestinationWithOffsets();

            //This is needed to get an accurate calculation on distance covered BEFORE applying the Y Arc offset, which interferes with the actual length calculated by GetCurrentDistance()
            //translator.transform.position = positionBeforeOffset;

            currentDistance = (destinationWithOffsets - positionBeforeYArcOffset).magnitude;

            //Closer the translator is to the destination, the higher the percent
            distanceCoveredPercent = 1 - (currentDistance / startingDistance);

            ///Application of max speed (after application of <see cref="ITouchTranslationProfile.SpeedScalePercent"/>), by total distance proximity
            float speedFactor = speedByProximityFactor.Evaluate(distanceCoveredPercent);

            newPosition = Vector3.MoveTowards(translator.transform.position, destinationWithOffsets, (speed * speedFactor) * Time.deltaTime);
            LogVector3Explicit(newPosition, "position before YArc:");
            positionBeforeYArcOffset = newPosition;//Set this for next frame so that CurrentDistance can be accurately calculated
            SetArcOffsetOnNewPosition();//Apply YArc to the previously calculated NewPosition
            LogVector3Explicit(newPosition, "position after YArc:");
            translator.transform.position = newPosition;



            if (distanceCoveredPercent < 0.99f) normalizedHeading = (destinationWithOffsets - translator.transform.position).normalized;//Set the heading if we're almost done with translation
            if (hasProfile) profile.TranslationPercentComplete = distanceCoveredPercent; //translator may use this data for its own calculations
            if (distanceCoveredPercent >= 1.0f) hasArrived = true;
        }

        yield return null;
    }

    if (hasProfile) profile.OnArrival(normalizedHeading, speed);
    CoroutineByTranslator.Remove(translator);

    void SetArcOffsetOnNewPosition()
    {
        float yOffset = yArc.Evaluate(currentDistance);
        yOffset *= yArcProximityFactor;
        newPosition.y += yOffset;
    }

    Vector3 CalculateDestinationWithOffsets()
    {
        Vector3 finalPosition = destination.Transform.position + destination.Offset;
        if (hasProfile) finalPosition.y += profile.TransformToMeshEndLength;
        return finalPosition;
    }

    void LogVector3Explicit(Vector3 logMe, string name)
    {
        Debug.Log(name + " : " + logMe.x + ", " + logMe.y + ", " + logMe.z);

    }
}

Назначение «Профиль» из предоставленного Touchable переводчика (переводчик реализует Monobehavior и имеет ссылку на компонент, который реализует ITouchTranslatorProfile) является рассматриваемой переменной .

Вот пример кода с точками останова, чтобы проиллюстрировать проблему, возникающую при отладке (см. Окно «Просмотр»):

CodeExample

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...