My Script is incredibly laggy(Is making the game run at around 4fps) How do I fix?

I have been working on a Project for almost half a year, I have had to create my own models so it has been slow progress. I am no expert when it comes to programming and my code is incredibly messy and generally plain awfully made. The more I code the more my game runs slow, I understand that happens when you have more code but I think there is certainly something I can do to help my game run better. Any tips? Or perhaps from my code below possibly tell me if you spot anything immediately wrong with my code?

Again thank you all in Advance!

Here is SOME of my code.

Again, I have been working on this for ages and this isn’t even a half of it

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Frey : MonoBehaviour
{
    public UnityEngine.AI.NavMeshAgent Nav;
    public GameObject yerF;
    public GameObject playerBuildInterface;
    public GameObject T1F1buildInterface;
    public GameObject ResourceManager;
    public GameObject EnergySystem;
    public GameObject TheEnergie;
    public GameObject TheEnerging;
    public GameObject EnergyBar;
    public GameObject newObject1;
    public GameObject newObject2;
    public GameObject newYerf;
    public bool EnergyActive = false;
    public bool TransferingEnergy = false;
    public bool Collecting = false;
    public bool ONce = false;
    public bool isGd = false;
    public bool isCd = false;
    public bool stillStill = false;
    public bool tt = false;
    public float Ttimer = 1;
    public float timer = 0;

    //public bool Once = false;
   
    // Start is called before the first frame update
    void Start()
    {
        if (tt == false)
        {
            Nav = this.transform.parent.gameObject.GetComponent<UnityEngine.AI.NavMeshAgent>();
        }
       
        playerBuildInterface = GameObject.FindWithTag("Xy");
        T1F1buildInterface = GameObject.FindWithTag("Zy");
        ResourceManager = GameObject.FindWithTag("ResourceManager");
        EnergySystem = GameObject.FindWithTag("Wy");
        EnergySystem = EnergySystem.transform.GetChild(0).gameObject;
        newYerf = GameObject.FindWithTag("yerf");
        EnergyBar = GameObject.FindWithTag("EnergyBar");
    }

    void Update()
    {
        Vector3 mouse = Input.mousePosition;
        Ray castPoint = Camera.main.ScreenPointToRay(mouse);
        RaycastHit hit;

        if (Input.GetMouseButtonDown(0))
        {
            if (TransferingEnergy == true && isGd == false)
            {
                if (Physics.Raycast(castPoint, out hit, Mathf.Infinity))
                {
                   
                    if (hit.transform.tag != "Desert" && hit.transform.tag != "Untagged")
                    {
                        TheEnerging = hit.transform.gameObject;
                        TheEnergie = this.gameObject.transform.parent.gameObject;
                        isGd = true;
                    }
                   
                    else
                    {
                        TransferingEnergy = false;
                    }
                   
                }
            }

            if (Collecting == true && isCd == false)
            {
                if (Physics.Raycast(castPoint, out hit, Mathf.Infinity))
                {

                    if (hit.transform.tag != "Desert" && hit.transform.tag != "Untagged" && hit.transform.tag == "Iron")
                    {
                        TheEnerging = hit.transform.gameObject;
                        TheEnergie = this.gameObject.transform.parent.gameObject;
                        isCd = true;
                    }

                    else
                    {
                        Collecting = false;
                    }
                }
            }
        }
       

            if (TransferingEnergy == true)
            {
              if (isGd == true)
              {

                if (ONce == false)
                {
                    this.gameObject.transform.parent.gameObject.GetComponent<Energy>().BecomeStill = true;
                    Nav.destination = TheEnerging.transform.position;
                    transform.LookAt(TheEnerging.transform.position);
                }
                if (Input.GetMouseButtonDown(1) && TheEnergie.GetComponent<Energy>().BeingControlled == true)
                {
                    TransferingEnergy = false;
                }

                if (Physics.Raycast(this.gameObject.transform.parent.gameObject.transform.position, transform.forward, out hit, 2))
                {

                    if (hit.transform.gameObject.tag == TheEnerging.tag)
                    {
                        //stillStill = true;

                       

                        if (TheEnerging == null)
                        {
                            TransferingEnergy = false;
                        }


                        if (TheEnergie == TheEnerging)
                        {
                            TransferingEnergy = false;
                        }

                        if (TheEnergie.GetComponent<Energy>().Enrgy > 0 && TheEnerging.GetComponent<Energy>().NeedEnergy == true)
                        {
                     


                            if (TheEnergie.GetComponent<Energy>().isStill == false || TheEnerging.GetComponent<Energy>().isStill == false)
                            {
                                TransferingEnergy = false;
                                ONce = false;
                                Destroy(newObject1);
                                Destroy(newObject2);

                            }

                            if (ONce == true)
                            {
                                TheEnergie.GetComponent<Energy>().Enrgy -= Time.deltaTime * TheEnergie.GetComponent<Energy>().OutPutR;
                                TheEnerging.GetComponent<Energy>().Enrgy += Time.deltaTime * TheEnergie.GetComponent<Energy>().OutPutR;
                            }

                            else
                            {
                                ONce = true;
                                TheEnerging.GetComponent<PlaceHolder>().Frey = this.gameObject;
                                newObject1 = Instantiate(EnergyBar, TheEnergie.transform.position + new Vector3(0, 2, 0), Quaternion.identity) as GameObject;
                                newObject2 = Instantiate(EnergyBar, TheEnerging.transform.position + new Vector3(0, 2, 0), Quaternion.identity) as GameObject;
                            }
                           






                            if (ONce == true)
                            {
                                newObject1.transform.GetChild(0).gameObject.GetComponent<ScaleEngBar>().Decay = TheEnergie.GetComponent<Energy>().Enrgy;
                                newObject1.transform.GetChild(0).gameObject.GetComponent<ScaleEngBar>().PrevDecay = TheEnergie.GetComponent<Energy>().MaxEnrgy;
                                //newObject1.GetComponent<LoadingBar>().Howmuch = 0.4f;
                                //newObject1.GetComponent<LoadingBar>().EnergyBar = true;
                                newObject2.transform.GetChild(0).gameObject.GetComponent<ScaleEngBar>().Decay = TheEnerging.GetComponent<Energy>().Enrgy;
                                newObject2.transform.GetChild(0).gameObject.GetComponent<ScaleEngBar>().PrevDecay = TheEnerging.GetComponent<Energy>().MaxEnrgy;
                                //w newObject2.GetComponent<LoadingBar>().Howmuch = 0.4f;
                                //newObject2.GetComponent<ScaleEngBar>().EnergyBar = true;
                            }

                        }
                    }
                    /*else
                    {
                        //if (stillStill == true)
                        //{
                            TransferingEnergy = false;
                            //stillStill = false;
                            TheEnerging = null;
                            TheEnergie = null;
                        //}
                    }
                    */
                }

              }           
            }
          else
          {
            isGd = false;
            if (newObject1 != null)
            {

                newObject1.GetComponent<Look>().ded = true;
                newObject2.GetComponent<Look>().ded = true;
                Destroy(newObject1);

                Destroy(newObject2);

                ONce = false;
            }
          }


        if (Collecting == true)
        {
            if (isCd == true)
            {
                if (ONce == false)
                {
                    this.gameObject.transform.parent.gameObject.GetComponent<Energy>().BecomeStill = true;
                    Nav.destination = TheEnerging.transform.position;
                    transform.LookAt(TheEnerging.transform.position);
                }

                if (Physics.Raycast(this.gameObject.transform.parent.gameObject.transform.position, transform.forward, out hit, 2))
                {
                    if (hit.transform.gameObject.tag == TheEnerging.tag)
                    {
                        //stillStill = true;

                        if (Input.GetMouseButtonDown(1) && TheEnergie.GetComponent<Energy>().BeingControlled == true)
                        {
                            Collecting = false;
                        }

                        if (TheEnerging == null)
                        {
                            Collecting = false;
                        }


                        if (TheEnergie == TheEnerging)
                        {
                            Collecting = false;
                        }

                        if (TheEnergie.GetComponent<Energy>().Enrgy > 0 && TheEnerging.GetComponent<Iron>().Durability > 0)
                        {
                            if (TheEnergie.GetComponent<Energy>().isStill == false || TheEnerging.GetComponent<Iron>().Durability == 0 || TheEnerging.GetComponent<Iron>().Durability < 0)
                            {
                                Collecting = false;
                                ONce = false;
                                Destroy(newObject1);
                                Destroy(newObject2);

                            }

                            TheEnergie.GetComponent<Energy>().Enrgy -= Time.deltaTime * TheEnergie.GetComponent<Energy>().Damage;
                            TheEnerging.GetComponent<Iron>().Durability -= Time.deltaTime * TheEnergie.GetComponent<Energy>().Damage;
                            if (TheEnerging.GetComponent<Iron>().Resource == "Iron")
                            {
                                timer += Time.deltaTime;
                                if (timer > Ttimer)
                                {
                                    timer = 0;
                                    int inter;
                                    inter = Random.Range(-2, 2);
                                    if (inter < 0)
                                    {
                                        inter = 0;
                                    }
                                    ResourceManager.GetComponent<ResourceManager>().Iron += inter;
                                }
                            }





                            if (ONce == false)
                            {
                                newObject1 = Instantiate(EnergyBar, TheEnergie.transform.position + new Vector3(0, 2, 0), Quaternion.identity) as GameObject;
                                newObject2 = Instantiate(EnergyBar, TheEnerging.transform.position + new Vector3(0, 2, 0), Quaternion.identity) as GameObject;
                                ONce = true;
                                Nav.destination = TheEnergie.transform.position;
                                TheEnerging.GetComponent<PlaceHolder>().Frey = this.gameObject;

                            }

                            if (ONce == true)
                            {
                                newObject1.transform.GetChild(0).gameObject.GetComponent<ScaleEngBar>().Decay = TheEnergie.GetComponent<Energy>().Enrgy;
                                newObject1.transform.GetChild(0).gameObject.GetComponent<ScaleEngBar>().PrevDecay = TheEnergie.GetComponent<Energy>().MaxEnrgy;
                                //newObject1.GetComponent<LoadingBar>().Howmuch = 0.4f;
                                //newObject1.GetComponent<LoadingBar>().EnergyBar = true;
                                newObject2.transform.GetChild(0).gameObject.GetComponent<ScaleEngBar>().Decay = TheEnerging.GetComponent<Iron>().Durability;
                                newObject2.transform.GetChild(0).gameObject.GetComponent<ScaleEngBar>().PrevDecay = TheEnerging.GetComponent<Iron>().OriginalDurability;
                                //w newObject2.GetComponent<LoadingBar>().Howmuch = 0.4f;
                                //newObject2.GetComponent<ScaleEngBar>().EnergyBar = true;
                            }

                        }
                    }
                    /*else
                    {
                        //if (stillStill == true)
                        //{
                            TransferingEnergy = false;
                            //stillStill = false;
                            TheEnerging = null;
                            TheEnergie = null;
                        //}
                    }
                    */
                }

            }
        }
        else
        {
            if (newObject1 != null)
            {
                if (isCd == true)
                {
                    newObject1.GetComponent<Look>().ded = true;
                    newObject2.GetComponent<Look>().ded = true;
                    Destroy(newObject1);

                    Destroy(newObject2);

                    ONce = false;
                }

            }
            isCd = false;

        }
       
    }

    // Update is called once per frame
    public void frey()
    {
        yerF.GetComponent<Teir1DroneFactory>().CreatingDroneT1 = true;
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DroneT1F1 : MonoBehaviour
{
    public bool BeingControlled = false;
    public GameObject Player;
    public float Energy = 100;
    public float MaxEnergy = 100;
    public float Speed = 2.5f;
    public UnityEngine.AI.NavMeshAgent Nav;
    public bool GivingEnergy = false;
    public GameObject Frey;
    public RaycastHit hit;
    public float Damage = 1;

    void Start()
    {
        Player = GameObject.FindWithTag("Player");
        Nav = GetComponent<UnityEngine.AI.NavMeshAgent>();
        Upgraded();
        Frey = this.transform.GetChild(0).gameObject;
        //GameObject.FindWithTag("Frey");
    }

    void Upgraded()
    {
        Nav.speed = Speed;
        GetComponent<Energy>().Damage = Damage;
    }

    void Update()
    {
        Vector3 mouse = Input.mousePosition;
        Ray castPoint = Camera.main.ScreenPointToRay(mouse);
        RaycastHit hit;


       
       
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            BeingControlled = false;
        }


        if (Input.GetMouseButtonDown(1) && BeingControlled == true)
        {

            GivingEnergy = false;
            /*if (Energy < 0)
            {
               
            }*/
            if (Energy > 1)
            {
                //GameObject newObject;
                //newObject = Instantiate(DartThrower, new Vector3(mousePos.x / -42.952f, -30.945f, mousePos.z / -29.506f), Quaternion.identity) as GameObject;

               
                if (Physics.Raycast(castPoint, out hit, Mathf.Infinity))
                {
                    Nav.destination = hit.point;
                    transform.LookAt(hit.point);
                   
                }
            }
        }
       
        if (Energy > MaxEnergy)
        {
            Energy = MaxEnergy;
        }

        if (Input.GetMouseButtonDown(0))
        {


            if (Physics.Raycast(castPoint, out hit, Mathf.Infinity))
            {
                if (hit.transform.gameObject.tag == "Player")
                {
                    BeingControlled = false;
                }
            }

            if (BeingControlled == true)
            {
                GameObject.FindWithTag("yerf").GetComponent<Yerf>().yerf1 = this.gameObject.transform.GetChild(0).gameObject;
            }
        }

        Frey.GetComponent<Frey>().EnergyActive = GivingEnergy;
    }


}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Teir1DroneFactory : MonoBehaviour
{
    public bool IsClicked = false;
    public GameObject playerBuildInterface;
    public GameObject T1F1buildInterface;
    public GameObject DroneT1;
    public GameObject ResourceManager;
    public GameObject LoadingBar;
    public bool CreatingDroneT1 = false;
    public float DDD = 20;
    public float Energy = 50;
    public float MaxEnergy = 500;
    public bool NeedEnergy = true;
    public bool NoEnergy = false;
    public bool ONce = false;
    public GameObject Frey;
    // Start is called before the first frame update
    void Start()
    {

        Frey = GameObject.FindWithTag("Frey");
        playerBuildInterface = GameObject.FindWithTag("Xy");
        T1F1buildInterface = GameObject.FindWithTag("Zy");
        T1F1buildInterface = T1F1buildInterface.transform.GetChild(0).gameObject;
        ResourceManager = GameObject.FindWithTag("ResourceManager");
        LoadingBar = GameObject.FindWithTag("LoadingBar");
        LoadingBar.tag = "Finish";
        LoadingBar.GetComponent<LoadingBar>().Decay = DDD;
        LoadingBar.GetComponent<LoadingBar>().Howmuch = 1;
        Energy = 50;
    }

    // Update is called once per frame
    public void CreateThink()
    {
       if (ResourceManager.GetComponent<ResourceManager>().Iron > 99 )
        {
            CreatingDroneT1 = true;
        }
       else
        {
            CreatingDroneT1 = false;
        }
    }
   
    void Update()
    {
       
        //this.GameObject.GetComponent<
        if (Energy < MaxEnergy)
        {
            NeedEnergy = true;
        }
        else
        {
            NeedEnergy = false;
        }
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            T1F1buildInterface.SetActive(false);
            playerBuildInterface.SetActive(true);
        }
        if (Input.GetMouseButtonDown(0))
        {
            /*if (T1F1buildInterface.activeInHierarchy == true)
            {
                T1F1buildInterface.SetActive(false);
                playerBuildInterface.SetActive(true);
            }*/

            //GameObject newObject;
            //newObject = Instantiate(DartThrower, new Vector3(mousePos.x / -42.952f, -30.945f, mousePos.z / -29.506f), Quaternion.identity) as GameObject;

       


        }
        GameObject newObject;
        if (CreatingDroneT1 == true)
        {
            if (ResourceManager.GetComponent<ResourceManager>().Iron > 99)
            {


                if (Energy > 0)
                {
                    GetComponent<Energy>().Enrgy -= Time.deltaTime;
                    if (ONce == false)
                    {
                        newObject = Instantiate(LoadingBar, transform.position + new Vector3(0, 2, 0), Quaternion.identity) as GameObject;
                        ONce = true;
                    }
                    DDD -= Time.deltaTime;
                    if (DDD < 0.5f)
                    {
                        CreatingDroneT1 = false;
                        newObject = Instantiate(DroneT1, transform.position + new Vector3(4, 0, 4), Quaternion.identity) as GameObject;
                        DDD = 20;
                        ONce = false;
                        ResourceManager.GetComponent<ResourceManager>().Iron -= 100;

                    }
                }
                else
                {
                    CreatingDroneT1 = false;
                }
            }
            else
            {
                CreatingDroneT1 = false;
            }
           
        }
    }
   
}

Again thank you all in Advance! :slight_smile:

Just Quick Edit, for Reference my game is a top down game, in a way like Starcraft, with it’s build system and top down veiw

I just skimmed through, but I don’t see anything outrageous in any of those scripts. Do you have thousands of instances running at the same time, maybe?

EDIT: btw, Unity has a built-in tool specially for finding script slowdowns.

With this tool you can see a break-down of everything that happens in a single frame. Look for the items that are taking-up the most time.

1 Like

Staring at code for performance analysis will only get you so far, in terms of “only the obvious stuff.”

I don’t see any crazy loops above (as @kdgalla notes) so I assume the lag is either somewhere else, or you simply have too many of these things all at once.

The solution to performance in computers is almost always to do less stuff, or to do it less frequently, and obviously to be clever about doing the stuff the player can see, the stuff the player cares about.

Otherwise, you kinda gotta start with the profiler, see what’s dogging you down. Here’s the general blurb:

DO NOT OPTIMIZE “JUST BECAUSE…” If you don’t have a problem, DO NOT OPTIMIZE!

If you DO have a problem, there is only ONE way to find out. Always start by using the profiler:

Window → Analysis → Profiler

Failure to use the profiler first means you’re just guessing, making a mess of your code for no good reason.

Not only that but performance on platform A will likely be completely different than platform B. Test on the platform(s) that you care about, and test to the extent that it is worth your effort, and no more.

Remember that you are gathering information at this stage. You cannot FIX until you FIND.

Remember that optimized code is ALWAYS harder to work with and more brittle, making subsequent feature development difficult or impossible, or incurring massive technical debt on future development.

Don’t forget about the Frame Debugger either, available right near the Profiler in the menu system.

Notes on optimizing UnityEngine.UI setups:

At a minimum you want to clearly understand what performance issues you are having:

  • running too slowly?
  • loading too slowly?
  • using too much runtime memory?
  • final bundle too large?
  • too much network traffic?
  • something else?

If you are unable to engage the profiler, then your next solution is gross guessing changes, such as “reimport all textures as 32x32 tiny textures” or “replace some complex 3D objects with cubes/capsules” to try and figure out what is bogging you down.

Each experiment you do may give you intel about what is causing the performance issue that you identified. More importantly let you eliminate candidates for optimization. For instance if you swap out your biggest textures with 32x32 stamps and you STILL have a problem, you may be able to eliminate textures as an issue and move onto something else.

This sort of speculative optimization assumes you’re properly using source control so it takes one click to revert to the way your project was before if there is no improvement, while carefully making notes about what you have tried and more importantly what results it has had.

“Software does not run in a magic fairy aether powered by the fevered dreams of CS PhDs.” - Mike Acton

Hello! Sorry for late reply and thank you so much for replying so quickly!

I will take a look at this and tell you what I find, again thank you!

Thank you so much for your swift response, I am immediately going to see what I can do with the Profiler, I saw this as I was mid-way through trying to rewrite everyscript (which could have possibly taken weeks) so thank you so much I will see what I can do!

Ok, I have just came back after taking some runs at the game and it says whenever my frames drop that most of it is being used up by "Garbagecollector, Rather than my Scripts. I am not very if at all knowledgeable with this sort of thing, but, do you know how I can fix this, or if that is even possible? Once again thank you for your Swift Reply!

The verbosity in this code is … INSANE! :hushed:

A fine example:
this.gameObject.transform.parent.gameObject.GetComponent().BecomeStill = true;

This is the same as the above:
transform.parent.gameObject.GetComponent().BecomeStill = true;

And this one …
if (Physics.Raycast(this.gameObject.transform.parent.gameObject.transform.position, transform.forward, out hit, 2))

If you keep doing this you’ll end up writing something like this … this does not scale:

if (Physics.Raycast(this.gameObject.transform.parent.gameObject.transform.gameObject.transform.parent.gameObject.transform.parent.gameObject.transform.parent.gameObject.transform.parent.gameObject.transform.parent.gameObject.transform.parent.gameObject.transform.parent.gameObject.transform.parent.gameObject.transform.parent.gameObject.transform.parent.position, transform.forward, out hit, 2))

newObject1.transform.GetChild(0).gameObject.GetComponent<ScaleEngBar>().Decay = TheEnergie.GetComponent<Energy>().Enrgy;
newObject1.transform.GetChild(0).gameObject.GetComponent<ScaleEngBar>().PrevDecay = TheEnergie.GetComponent<Energy>().MaxEnrgy;
newObject2.transform.GetChild(0).gameObject.GetComponent<ScaleEngBar>().Decay = TheEnerging.GetComponent<Energy>().Enrgy;
newObject2.transform.GetChild(0).gameObject.GetComponent<ScaleEngBar>().PrevDecay = TheEnerging.GetComponent<Energy>().MaxEnrgy;

There is a thing called ‘variables’. You may have heard about them? Don’t be afraid to use them! It makes your code way more readable, and there’s no wasted performance due to repeatedly running the same methods over and over and over again:

var engBar1 = newObject1.transform.GetChild(0).gameObject.GetComponent<ScaleEngBar>();
var engBar2 = newObject2.transform.GetChild(0).gameObject.GetComponent<ScaleEngBar>();
var energie = TheEnergie.GetComponent<Energy>();
var energing = TheEnergie.GetComponent<Energy>();

engBar1.Decay = engBar1.PrevDecay = energie.Enrgy;
engBar2.Decay = engBar2.PrevDecay = energing.Enrgy;

Also check your spelling, too. Refactor rename those, it just takes two seconds to change MaxEnrgy into MaxEnergy. Similarly, I’m sure you’ve mixed up TheEnergy and TheEnerging - those are awfully similar.

Garbage collection issues might happen when you are constantly allocating and freeing a lot of memory. There are a lot of articles about garbage collection in Unity on the internet. These should give you tips on how to avoid unnecessary allocations.
i.e.

Instantiating and deleting objects (for example) can cause garbage collection, but (once again) it shouldn’t really be a problem unless you are doing this thousands of times per frame.

The first thing you should do is remove every “GameObject.Find…” in your Start() methods and assign them in the Inspector. GameObject.Find must be used as scarcely as possible.
Do the same about every line that use “GetComponent” as @CodeSmile already hinted at.
Same thing for “Transform.Find” if you have some and any line that requires getting something or finding something.
After that, Unity should feel a little better. :wink:

Let me also add that BEFORE you wreck anything about your project, make sure you have it fully backed up and under proper source control, otherwise you could lose all your work tearing up what you have.

PROPERLY CONFIGURING AND USING ENTERPRISE SOURCE CONTROL

I’m sorry you’ve had this issue. Please consider using proper industrial-grade enterprise-qualified source control in order to guard and protect your hard-earned work.

Personally I use git (completely outside of Unity) because it is free and there are tons of tutorials out there to help you set it up as well as free places to host your repo (BitBucket, Github, Gitlab, etc.).

You can also push git repositories to other drives: thumb drives, USB drives, network drives, etc., effectively putting a complete copy of the repository there.

As far as configuring Unity to play nice with git, keep this in mind:

https://discussions.unity.com/t/736093/3

I usually make a separate repository for each game, but I have some repositories with a bunch of smaller test games.

Here is how I use git in one of my games, Jetpack Kurt:

https://discussions.unity.com/t/807568/3

Using fine-grained source control as you work to refine your engineering:

https://discussions.unity.com/t/826718/2

Share/Sharing source code between projects:

https://discussions.unity.com/t/719810/2

Setting up an appropriate .gitignore file for Unity3D:

https://discussions.unity.com/t/834885/5

Generally the ONLY folders you should ever source control are:

Assets/
ProjectSettings/
Packages/

NEVER source control Library/ or Temp/ or Logs/
NEVER source control anything from Visual Studio (.vs, .csproj, none of that noise)

Setting git up with Unity (includes above .gitignore concepts):

It is only simple economics that you must expend as much effort into backing it up as you feel the work is worth in the first place. Digital storage is so unbelievably cheap today that you can buy gigabytes of flash drive storage for about the price of a cup of coffee. It’s simply ridiculous not to back up.

If you plan on joining the software industry, you will be required and expected to know how to use source control.

Source control does require learning, but there are TONS of tutorials and courses and online reference.

You should strive to use source control as well as you use your file/folder system.

“Use source control or you will be really sad sooner or later.” - StarManta on the Unity3D forum boards

Other than that, everything posted above is spot-on… this script needs to be DRASTICALLY simplified in many ways.

Remember the first rule of GameObject.Find():

Do not use GameObject.Find();

More information: https://starmanta.gitbooks.io/unitytipsredux/content/first-question.html

More information: https://discussions.unity.com/t/899843/12

In general, DO NOT use Find-like or GetComponent/AddComponent-like methods unless there truly is no other way, eg, dynamic runtime discovery of arbitrary objects. These mechanisms are for extremely-advanced use ONLY.
If something is built into your scene or prefab, make a script and drag the reference(s) in. That will let you experience the highest rate of The Unity Way™ success of accessing things in your game.

Keep in mind that using GetComponent() and its kin (in Children, in Parent, plural, etc) to try and tease out Components at runtime is definitely deep into super-duper-uber-crazy-Ninja advanced stuff.

Here’s the bare minimum of stuff you absolutely MUST keep track of if you insist on using these crazy Ninja methods:

  • what you’re looking for:
    → one particular thing?
    → many things?
  • where it might be located (what GameObject?)
  • where the Get/Find command will look:
    → on one GameObject? Which one? Do you have a reference to it?
    → on every GameObject?
    → on a subset of GameObjects?
  • what criteria must be met for something to be found (enabled, named, etc.)

If you are missing knowledge about even ONE of the things above, your call is likely to FAIL.

This sort of coding is to be avoided at all costs unless you know exactly what you are doing.

Botched attempts at using Get- and Find- are responsible for more crashes than useful code, IMNSHO.

If you run into an issue with any of these calls, start with the documentation to understand why.

There is a clear set of extremely-well-defined conditions required for each of these calls to work, as well as definitions of what will and will not be returned.

In the case of collections of Components, the order will NEVER be guaranteed, even if you happen to notice it is always in a particular order on your machine.

It is ALWAYS better to go The Unity Way™ and make dedicated public fields and drag in the references you want.

The immediate thing that jumped out at me was that everything is all in update… I haven’t gone through every line but judging from the syntax used I have a feeling all your scripts may be like this. Update is called every single frame. There are probably many things you don’t want to be calling like that. Put them in their own methods and call them when you need them. Also it’s best to do this even if you need them called from update so that you don’t have an update method hundreds of lines long. Also about it being related to garbage collecting you are making many local variables in update directly… this is unnecessary, make them/ cache them at the top of your script.

You have a fair point, though I have the Frey gameObject on/ as child to every Drone in the game, so the .parent is to get the Drone! thank you though!

Thank you so so much for your in-depth respone! I had no idea that I wasn’t supposed to be always using GameObject.Find, so thank you! I have made a backup as well so thank you again!

Thank you, that is very reasonable, I was mostly just being lazy with them, thank you I will edit out the ones that are not proper variables, I didn’t realize they would effect my game, once again thank you!

Thank you so much, I will do that right away! Though as @CodeSmile suggested, there is only certain times you should use them, is there any good example of a time I should use them?

There’s really never a good time to use gameibject.find, the meme of the first rule being not to use it exists because there is always a better way to get a reference to the object you need. Im doubtful anyone could give a good example of a time it should be used.

Getcomponent on the other hand is fine to use, you just don’t want to call it repeatedly when you don’t need to.ie - directly in update or when you need the reference multiple times and should be assigning it to a variable

Brilliant! Thank you for explaining!

Also as @Kurt-Dekker often say, if you have more than 2 dots in a line of code, you’re being mean to yourself. Example:

// 3 dots... bad
otherGameObject.GetComponent<SomeScript>().SomeProperty.Value =  5;

// Do this instead
var someScript = otherGameObject.GetComponent<SomeScript>();
someScript.SomeProperty.Value = 5;

// Bonus, you can access "someScript" in the next lines
// without a need to call GetComponent<SomeScript>() again
// => better readability and performance
1 Like