Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by arjuniscool0204 · Jan 08, 2020 at 09:34 AM · performanceoptimizationvariablesweapon systemscript referencing

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! :)

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

215 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Getting low fps on a very simple scene 0 Answers

Best way to make a huge terrain for flight simulator? 1 Answer

same material for different texture ? to increase performance 1 Answer

Choosing best mobile performance solutions 1 Answer

UI performance. FPS drops. Overdraw. 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges