Return gameobject from raycast

I have a script where I call a function called Raycast in the update function. The Raycast function sends out a raycastall and I want to return the gameObject I hit with the raycast so I can access a script on it. How would I do this?

The scripts look something like:

void update()
{
if(some_boolean)
{
Raycast();
}
}


void Raycast()
{
RaycastHit[] hits;
hits = Physics.RaycastAll(mainCam.transform.position, mainCam.transform.forward);

//And so on..
}

See that hits array? That’s going to contain all the things you hit. You can go through it and check for example hits[0].collider.gameObject

What I did was in my update function, when I a booleans was true, I called a GameObject Function where I cast a Raycast and return the object I hit.

Something like this:

void Update()
{
if(some_boolean)
{
GameObject hit = Raycast();

//Do something with the gameObject

}
}

GameObject Raycast()
{
//Send Raycast
return ObjectHit;
}