How to reference a script from another script to access multiple variables in unity c#

137 Views Asked by At

Hello I have 2 script my recoil script and my gunystem script

I have my recoil script on my camera recoil obj as a child of camera rot obj

I have my gunsystem script on multiple guns

i am trying to make all guns have different recoil

how do i do this I am new to C# and unity and this is my first game

Where the recoil Script is placed

My Recoil Script: Note: Just a part of the script

using UnityEngine;

public class Recoil : MonoBehaviour
{


    //Rotations
    private Vector3 currentRotation;
    private Vector3 targetRotation;

    //Hipfire Recoil
    public float recoilX;
    public float recoilY;
    public float recoilZ;

    //Settings
    public float snappiness;
    public float returnSpeed;

    void Start()
    {

    }













My GunSystem Script: Note: Just a part of the script

using UnityEngine;
using TMPro;

public class GunSystem : MonoBehaviour
{
    //Gun stats
    public int damage;
    public float timeBetweenShooting, spread, range, reloadTime, timeBetweenShots;
    public int magazineSize, bulletsPerTap;
    public bool allowButtonHold;
    int bulletsLeft, bulletsShot;

    //bools 
    bool shooting, readyToShoot, reloading;

    //Reference
    public Camera fpsCam;
    public Transform attackPoint;
    public RaycastHit rayHit;
    public LayerMask whatIsEnemy;

    //Graphics
    public GameObject muzzleFlash, bulletHoleGraphic;
    public TextMeshProUGUI text;









I tried placing these variables in the gunsystem script:

 //Hipfire Recoil
    public float recoilX;
    public float recoilY;
    public float recoilZ;

    //Settings
    public float snappiness;
    public float returnSpeed;

and refrencing the script in the recoil script but i dont know how to refrence a script that is an different game obj and how to refrence multiple variables.

1

There are 1 best solutions below

1
Leo On
public class Gun : MonoBehaviour
{

    //Hipfire Recoil
    public static float recoilX = 10f;

}

Access variables like this:

public class Recoil : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        print(Gun.recoilX); // 10
    }
}