Home > database >  Is there a way to reference a RaycastHit of a raycast outside of the void the raycast was made in? (
Is there a way to reference a RaycastHit of a raycast outside of the void the raycast was made in? (

Time:12-17

i want to access the local variable raycastHit from outside of this void i made it in, is that possible?

private void HandleHookShotStart()
    {
        

        if (TestInputDownHookShot())
        {
            if (Physics.Raycast(Shoulder.transform.position, cam.transform.forward, out RaycastHit raycastHit))
            {
                //Hit Something
                debugHitpointTransform.position = raycastHit.point;
                hookshotPosition = raycastHit.point;
                hookShotSize = 0f;
                HookShotTransform.gameObject.SetActive(true);
                HookShotTransform.localScale = Vector3.zero;

                state = State.HookShotThrown;
            }
        }
    }

CodePudding user response:

Usually you will have a RaycastHit variable as a class variable. Making it private you can access it from any part of the code within the class and making it public from anywhere. In both cases you will be able to access the raycastHit variable from outside the void method.

publuic RaycastHit raycastHit; 
private void HandleHookShotStart()
{
    if (TestInputDownHookShot())
    {
        if (Physics.Raycast(Shoulder.transform.position, cam.transform.forward, out raycastHit)) //type RaycastHit  removed in the call
        {
            //Hit Something
            debugHitpointTransform.position = raycastHit.point;
            hookshotPosition = raycastHit.point;
            hookShotSize = 0f;
            HookShotTransform.gameObject.SetActive(true);
            HookShotTransform.localScale = Vector3.zero;

            state = State.HookShotThrown;
        }
    }
}

Note that with out you are not creating the variable. "The out keyword causes arguments to be passed by reference" (docs). So when you call the raycast method with your class variable passed in, the value will be "filled" in. The value "filling" has nothing to do with the accesibity.Your variable will be accessible according to the access modifier set at the variable declaration, public/private or other.

  • Related