Referencing variables from another script each time it is needed.
Hi guys! I'm currently making a fps multiplayer sci- fi game. I have a GunManager script that takes care of shooting, reloading and gun switching. this script gets variables from another script called GunInfo which contains all the details like animator, bullets, speed, muzzleflash etc. Currently i'm accessing variables from guninfo whenever the gun manager needs it. But i wonder if the way i'm doing this affects performance in any way? The scripts are below :
Gun Manager
private const string PLAYER_TAG = "Player";
[SyncVar]
public int selectedWeapon = 0;
[SyncVar]
public int previousSelectedWeapon;
[SyncVar]
public bool switching;
public bool canSwitch;
public bool shooting;
public bool reloading;
public Camera fpscam;
public LayerMask mask;
private Animator anim;
public int onlayer;
public int offlayer;
public float bulletForce;
//private GameManager gameManager;
public Transform gunHolder;
public List<int> holdedWeapons;
//public RawImage crossHair;
public GunInfo gunInfo;
private GunInfo inActivegunInfo;
public bool weaponUpdated = false;
//public Transform currentlyEquippedWeapon;
// Use this for initialization
void Awake ()
{
//gameManager = FindObjectOfType<GameManager> ();
anim = GetComponent<Animator> ();
canSwitch = true;
holdedWeapons = GameManager.weaponsToEquip;
SelectWeapons ();
//fpscam = GetComponentInChildren<Camera> ();
//gunHolder = transform.Find ("MainCamera").transform.Find ("GunHolder");
}
void SelectWeapons()
{
int i = 0;
foreach (Transform weapon in gunHolder.transform)
{
if (!holdedWeapons.Contains (i)) {
weapon.SetParent (this.transform);
weapon.gameObject.SetActive (false);
}
i++;
}
Switch ();
//currentlyEquippedWeapon = gunHolder.GetChild (selectedWeapon).transform;
}
// Update is called once per frame
void Update ()
{
if (PauseMenuScript.isOn)
return;
if (previousSelectedWeapon != selectedWeapon) {
Switch ();
}
if (!shooting & !reloading & !switching & isLocalPlayer) {
//SHOOT METHOD
if (gunInfo.currentBullets > 0) {
}
if (Input.GetMouseButton (0)) {
Shoot ();
} else if (gunInfo.fireType == "Rapid") {
if (Input.GetMouseButtonDown (0)) {
InvokeRepeating ("Shoot", 0f, gunInfo.fireRate);
} else if (Input.GetMouseButtonUp (0)) {
CancelInvoke ("Shoot");
}
}
//RELOAD METHOD
if (gunInfo.storedBullets > 0) {
if (gunInfo.currentBullets == 0 & Input.GetMouseButton (0)) {
StartCoroutine (Reload ());
} else if (gunInfo.currentBullets < gunInfo.magazineSize & Input.GetKeyDown (KeyCode.R))
StartCoroutine (Reload ());
}
float middleMouse = Input.GetAxis ("Mouse ScrollWheel");
//SWITCHING METHOD
if (canSwitch) {
if (Input.GetKeyDown (KeyCode.G) & canSwitch == true) {
CmdSwitchWeapon (1f);
} else if (middleMouse > 0f) {
CmdSwitchWeapon (1f);
} else if (middleMouse < 0f) {
CmdSwitchWeapon (-1f);
}
}
}
//if (isLocalPlayer) {
//GameObject.Find ("CurrentBullets").GetComponent<Text> ().text = gunInfo.currentBullets.ToString ();
//GameObject.Find ("StoredBullets").GetComponent<Text> ().text = gunInfo.storedBullets.ToString ();
//}
//crossHair.transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
//Calling the server when player shoots
[Command]
void CmdOnShoot()
{
RpcShootEffect ();
}
//Called on all clients by server
[ClientRpc]
void RpcShootEffect()
{
gunInfo.muzzleFlash.Play ();
}
[Command]
void CmdOnHit(Vector3 _pos, Vector3 _normal)
{
RpcHitEffect (_pos,_normal);
}
[ClientRpc]
void RpcHitEffect(Vector3 _pos, Vector3 _normal)
{
Instantiate (gunInfo.impactEffect, _pos, Quaternion.LookRotation (_normal));
}
[Client]
public void Shoot()
{
//if (gunInfo.currentBullets == 0 & gunInfo.storedBullets != 0) {
//StartCoroutine (Reload ());
//yield break;
//} else if (gunInfo.currentBullets == 0 & gunInfo.storedBullets == 0) {
//yield break;
//}
if (gunInfo.currentBullets > 0 & !shooting) {
shooting = true;
StartCoroutine(ShootAnim());
canSwitch = false;
CmdOnShoot ();
gunInfo.currentBullets--;
gunInfo.gunSound.Play ();
RaycastHit hit;
if (Physics.Raycast (fpscam.transform.position, fpscam.transform.forward, out hit, gunInfo.range, mask)) {
//Debug.Log (hit.transform.name);
//IMPACT EFFECT
CmdOnHit(hit.point, hit.normal);
ObjectHealth target = hit.transform.GetComponent<ObjectHealth> ();
if (target != null) {
target.TakeDamage (gunInfo.damageAmt);
}
if (hit.collider.tag == PLAYER_TAG) {
CmdPlayerShot (hit.collider.name, gunInfo.damageAmt);
//Debug.Log ("Reached here?");
}
}
//yield return new WaitForSeconds (gunInfo.shootDelay);
//BULLETS!!!!!!Shells...
GameObject bullet = Instantiate (gunInfo.bulletPrefab, gunInfo.shellSpawnPoint.position,gunInfo.shellSpawnPoint.rotation);
bullet.GetComponent<ShellWork> ().Go (bulletForce);
Destroy (bullet, 2f);
}
//yield break;
}
IEnumerator ShootAnim()
{
anim.SetBool ("shoot", true);
yield return new WaitForSeconds (gunInfo.shootDelay);
anim.SetBool ("shoot", false);
shooting = false;
canSwitch = true;
yield break;
}
[Client]
IEnumerator Reload()
{
reloading = true;
canSwitch = false;
anim.SetBool ("reload", true);
gunInfo.gunReload.Play ();
yield return new WaitForSeconds (2f);
if (gunInfo.storedBullets < gunInfo.magazineSize) {
int bulletDiff = gunInfo.magazineSize - gunInfo.currentBullets;
if (gunInfo.storedBullets > bulletDiff) {
gunInfo.currentBullets += bulletDiff;
gunInfo.storedBullets -= bulletDiff;
} else {
gunInfo.currentBullets += gunInfo.storedBullets;
gunInfo.storedBullets -= gunInfo.storedBullets;
}
} else {
int bulletDifference = gunInfo.magazineSize - gunInfo.currentBullets;
gunInfo.currentBullets += bulletDifference;
gunInfo.storedBullets -= bulletDifference;
}
reloading = false;
canSwitch = true;
anim.SetBool ("reload", false);
yield break;
}
[Client]
void Switch()
{
canSwitch = false;
switching = true;
weaponUpdated = false;
int i = 0;
foreach (Transform weapon in gunHolder.transform) {
if (i == selectedWeapon) {
weapon.gameObject.SetActive (true);
previousSelectedWeapon = selectedWeapon;
gunInfo = weapon.GetComponent<GunInfo> ();
weaponUpdated = true;
onlayer = anim.GetLayerIndex (gunInfo.name);
anim.SetLayerWeight (onlayer, 1);
}
if (i != selectedWeapon) {
inActivegunInfo = weapon.GetComponent<GunInfo> ();
weapon.gameObject.SetActive (false);
offlayer = anim.GetLayerIndex (inActivegunInfo.name);
anim.SetLayerWeight (offlayer, 0);
}
i++;
StartCoroutine(SwitchDelay ());
}
/*guns [activeGun].SetActive (false);
if (activeGun == guns.Length - 1) {
activeGun = 0;
} else {
activeGun += 1;
}
guns [activeGun].SetActive (true);*/
}
[Client]
IEnumerator SwitchDelay()
{
yield return new WaitForSeconds (0.1f);
switching = false;
canSwitch = true;
yield break;
}
[Command]
void CmdPlayerShot(string _playerID,float damage)
{
//Debug.Log (_playerID + " has been shot");
ThePlayer _player = GameManager.GetPlayer (_playerID);
_player.RpcTakeDamage (damage);
}
[Command]
void CmdSwitchWeapon(float type)
{
RpcSwitchWeapon (type);
}
[ClientRpc]
void RpcSwitchWeapon(float type)
{
if (type == 1) {
if (selectedWeapon == gunHolder.childCount - 1) {
selectedWeapon = 0;
} else {
selectedWeapon++;
}
} else if (type == -1) {
if (selectedWeapon == 0) {
selectedWeapon = gunHolder.childCount - 1;
} else {
selectedWeapon--;
}
}
}
// void GoBack() // { // fpscam.fieldOfView -= gunInfo.backAmt; // } // // void Normal() // { // fpscam.fieldOfView += gunInfo.backAmt; // // }
}
This is the Gun Info
public float range = 100f;
//public Camera fpscam;
//public Camera fpscam;
//private bool shooting;
public GameObject impactEffect;
public ParticleSystem muzzleFlash;
public Transform bulletSpawnPoint;
public GameObject bulletPrefab;
public Transform shellSpawnPoint;
public int storedBullets;
public int currentBullets;
public int magazineSize;
//private bool reloading;
//private GunManager gunHolder;
public float damageAmt = 10f;
public AudioSource gunSound;
public AudioSource gunReload;
public float backAmt;
public string GunName;
public float shootDelay;
public float fireRate;
public string fireType;
void Awake ()
{
gunSound = GameObject.Find (GunName +"Shot").GetComponent<AudioSource>();
gunReload = GameObject.Find (GunName +"Reload").GetComponent<AudioSource>();
}
}
As you can see I'm accessing variables by storing the guninfo script as reference and then getting all variables from that stored reference. It would be great if someone could clear this doubt. Currently if this causes performance loss I have 2 ideas. One is to store all these variables in the gun manager script at once instead of getting it again and again from the guninfo reference. The other idea i have is that i should shift all the functions like shooting, reloading to the guninfo scripts and only keep the weapon switching to gun manager script. Both these ideas look like they use some extra storage or memory. But maybe one of them improves performance? Basically what is the best way to go about this? Cheers! :)