Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved How can I optimize my code? THANKS EVERYONE

Discussion in 'Scripting' started by enesbagci2332, Aug 10, 2023.

  1. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    Well personally I use a Inheritance structure, so my first script that holds all the communication values or lists of instances, is where I also put my singleton references. I think I'm the only person on earth to do it this way. :rolleyes:

    But if you have a script that mostly communicates with everything, and is always existing, you can put:
    public static Player player;
    in that script, and in your Player.cs Awake() put:
    ExistingScriptName.player = this;
    .

    Or a more general way people sometimes put the same instance within the same script, so in Player.cs:
    Code (CSharp):
    1. public static Player instance;
    2.  
    3. void Awake()
    4. {
    5.    instance = this;
    6. }
    So in other scripts you just call:
    Code (CSharp):
    1. gasGaugeValue1 = ExistingScriptName.player.fuelLeft;
    2. // or
    3. gasGaugeValue1 = Player.instance.fuelLeft;
    But it all really depends on how you have your code setup, to which way would make more sense. Because understanding your own code is Rule#1. :)
     
    enesbagci2332 likes this.
  2. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    I will use this technic in a script now or later, thanks!