parallax effect flickering/shaking

I was trying to implement parallax background to my personal project using this tutorial but it’s doing this shaking/glitching thing. Here’s the gif. And it’s also going over the HUD which i assumed would be solved by changing the layer order but the backgrounds don’t have an option for that. I’d appreciate it if anyone could help me out :slight_smile:

Here’s my code.

using UnityEngine;

public class ParallaxController : MonoBehaviour
{
    Transform cam;
    Vector3 camStartPos;
    float distance; 

    GameObject[] backgrounds;
    Material[] mat;
    float[] backSpeed;

    float farthestBack;

    [Range(0f, 0.05f)]
    public float parallaxSpeed;

    void Start()
    {
        cam = Camera.main.transform;
        camStartPos = cam.position;

        int backCount = transform.childCount;
        mat = new Material[backCount];
        backSpeed = new float[backCount];
        backgrounds = new GameObject[backCount];

        for (int i = 0; i < backCount; i++)
        {
            backgrounds *= transform.GetChild(i).gameObject;*

mat = backgrounds*.GetComponent().material;*

}
BackSpeedCalculate(backCount);
}

void BackSpeedCalculate(int backCount)
{
for (int i = 0; i < backCount; i++)
{
if ((backgrounds*.transform.position.z - cam.position.z) > farthestBack)*
{
farthestBack = backgrounds*.transform.position.z - cam.position.z;*
}

}

for (int i = 0; i < backCount; i++)
{
backSpeed = 1 - (backgrounds*.transform.position.z - cam.position.z) / farthestBack;*
}
}

private void LateUpdate()
{
distance = cam.position.x - camStartPos.x;
transform.position = new Vector3(cam.position.x, cam.position.y, 0);
// The line above had cam.pos.x, transform.pos.y previously but
// changed it to cam.pos.y since i wanted it to follow the y axis as well.

for (int i = 0; i < backgrounds.Length; i++)
{
float speed = backSpeed * parallaxSpeed;
mat.SetTextureOffset("MainTex", new Vector2(distance, 0) * speed);
}
}
}_