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

Question Performance and storing player transform/position data

Discussion in 'Scripting' started by Mak992, Feb 20, 2021.

  1. Mak992

    Mak992

    Joined:
    Oct 2, 2018
    Posts:
    9
    Hello
    I am building an inventory where you can drop the item out from the inventory. I want it to drop from the players current position. Is there a way to store the transform data globally or another performant way. so i dont have to reference it everytime i use it on a script.

    And another question. If i want to instatiate a prefab i made etc a sword. What would be the easiest? to store the prefab on the "item" class or is there another method that i havent thought about.

    In advance Thank you
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,336
    Since a lot of things need to know player position, this is a good thing to put in a GameManager, either static or as a Unity singleton.

    Simple Singleton (UnitySingleton):

    Some super-simple Singleton examples to take and modify:

    Simple Unity3D Singleton (no predefined data):

    https://pastebin.com/SuvBWCpJ

    Unity3D Singleton with Prefab used for predefined data:

    https://pastebin.com/cv1vtS6G

    These are pure-code solutions, do not put anything into any scene, just access it via .Instance!

    If it is a GameManager, when the game is over, make a function in that singleton that Destroys itself so the next time you access it you get a fresh one, something like:

    Code (csharp):
    1. public void DestroyThyself()
    2. {
    3.    Destroy(gameObject);
    4.    Instance = null;    // because destroy doesn't happen until end of frame
    5. }
    Code (csharp):
    1. var newSword = Instantiate<GameObject>( SwordPrefab);
    That's always easiest. Start with that. If you need more organization or choices, start building it up from there.
     
  3. Mak992

    Mak992

    Joined:
    Oct 2, 2018
    Posts:
    9
    It works just as it should, thanks for the help
     
    Kurt-Dekker likes this.