首页 > 解决方案 > unity If & else 语句

问题描述

所以我有 5 个不同的对象,每次单击特定对象时,它们都应该按顺序放置。它似乎没有按顺序排列,而是跳过了第一个并进入了第二个。所以不是去check1,而是直接去check2。

这是我的代码:

if (IsBehindHeld == true)
    {
        Vector3 MousePos;
        MousePos = Input.mousePosition;
        MousePos = Camera.main.ScreenToWorldPoint(MousePos);


        if (Check1.transform.childCount != 1)
        {
            this.gameObject.transform.position = Check1.transform.position;
            _rb2.isKinematic = true;
            locked = true;

            this.transform.parent = Check1.transform;

        }

        else
        {
            if (Check2.transform.childCount != 1 )
            {
                this.gameObject.transform.position = Check2.transform.position;
                _rb2.isKinematic = true;
                locked = true;

                this.transform.parent = Check2.transform;

            }

            else
            {
                if (Check3.transform.childCount != 1)
                {
                    this.gameObject.transform.position = Check3.transform.position;
                    _rb2.isKinematic = true;
                    locked = true;

                    this.transform.parent = Check3.transform;

                }

                else
                {

                }
            }
        }

    }

标签: c#unity3d

解决方案


请发布有关检查碰撞器、对象层次结构和组件的更多信息,每个都必须了解更多。此外,如果您尝试使用 else if,它会更容易阅读:

if (IsBehindHeld == true)
        {
            Vector3 MousePos;
            MousePos = Input.mousePosition;
            MousePos = Camera.main.ScreenToWorldPoint(MousePos);


            if (Check1.transform.childCount != 1)
            {
                this.gameObject.transform.position = Check1.transform.position;
                _rb2.isKinematic = true;
                locked = true;

                this.transform.parent = Check1.transform;

            }

            else if (Check2.transform.childCount != 1)
            {
                this.gameObject.transform.position = Check2.transform.position;
                _rb2.isKinematic = true;
                locked = true;

                this.transform.parent = Check2.transform;

            }
            else if (Check3.transform.childCount != 1)
            {
                this.gameObject.transform.position = Check3.transform.position;
                _rb2.isKinematic = true;
                locked = true;

                this.transform.parent = Check3.transform;

            }
        }

在 if 语句之后可以使用多个 else if 语句。它只会在 if 条件评估为 false 时执行。因此,可以执行 if 或 else if 语句之一,但不能同时执行。让我知道事情的后续!


推荐阅读