【问题标题】:bool value setting only execute once? then return to false in void布尔值设置只执行一次?然后在void中返回false
【发布时间】:2021-12-27 11:39:28
【问题描述】:

为什么我的布尔值设置只执行一次?然后返回false?当我执行它的功能时,设置为“true”一次,然后返回false。

private bool[] set = new[] { false, false, false, false};

void Update()
    {
        movefunc(setSpineRotates[0], "spinerotatecolor");
    }
 void movefunc(bool set, string co)
    {
        if (Input.touchCount == 1)
        {
            Touch screentouch = Input.GetTouch(0);
            Ray ray = camera.ScreenPointToRay(screentouch.position);
            if (screentouch.phase == TouchPhase.Began)
            {
                if (Physics.Raycast(ray, out RaycastHit hitInfo))
                {
                    if (hitInfo.collider.gameObject.GetComponent(co) != null)
                    {
                        set = true;
                    }
                }
            }
        }
        Debug.log(set);
        //. when i perform the function it, set to "true" once,then return to false.
        if (set)
        {
            sliderx.SetActive(true);
            slidery.SetActive(true);
            sliderz.SetActive(true);
        }
    }

所以当我执行函数时,它是否只复制值?

【问题讨论】:

  • 为什么set = true; 甚至编译¿? -> Cannot implicilty convert type bool to bool[]
  • @rustyBucketBay no 在 OP 的方法中还有参数 bool set 隐藏了外部 bool[] set ..
  • 哦,非常正确。谢谢
  • 请使用正确的标签!请注意,unityscript 是或更好的是曾经是一种 JavaScript 风格,类似于早期 Unity 版本中使用的自定义语言,并且现在已经不推荐使用了!你的代码在c# ..

标签: c# unity3d


【解决方案1】:

当布尔类型传递给函数时,它不是通过引用传递的。 该 bool 的一个新实例被创建,并且在该函数中,只有该实例被更改为 true。

要解决这个问题,您需要使用 ref 关键字传递它,或者使用 index[i] 作为参数,如下所示:

void movefunc(int index, string co)
{
    ...
    if (hitInfo.collider.gameObject.GetComponent(co) != null)
    {
        set[index] = true;
    } 
}

【讨论】:

    猜你喜欢
    • 2020-06-23
    • 2022-01-14
    • 2019-12-06
    • 2014-07-03
    • 2017-11-23
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    相关资源
    最近更新 更多