Home > Back-end >  bool value setting only execute once? then return to false in void
bool value setting only execute once? then return to false in void

Time:12-28

why my bool value setting only execute once? then return to false? when I perform the function it, is set to "true" once, then return to 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);
        }
    }

so when i perform the function, does it only copies the value?

CodePudding user response:

When bool type is passed to a function, it does not passed by reference. A new instance of that bool is created, and in that function, only that instance is changed to true.

To fix that you need either pass it with ref keyword, or use the index[i] as the parameter like so:

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