Search Unity

Giving player placed structures a unique ID need help.

Discussion in 'Scripting' started by Kenneth4848, Sep 19, 2017.

  1. Kenneth4848

    Kenneth4848

    Joined:
    Sep 14, 2017
    Posts:
    14
    I am trying to build a physics based building system where player placed structures can be pushed around with enough force. My problem is I want to be able to save the positions of each object in a way to where the game auto updates the data storing each object's position. In order to do this I had an idea to have each object given a unique ID that only it has. As the database which keeps track of the structures updates, it knows which position to update for which object because of the ids.

    Can anyone show me how to make a unique id generator? I have a feeling that instance id might not work.
     
  2. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    12,706
    Code (csharp):
    1. string uniqueID = System.Guid.NewGuid().ToString();
     
  3. SlyRipper

    SlyRipper

    Joined:
    Jun 19, 2012
    Posts:
    251
    What exactly are you planning to do? Do you need to save the positions throughout several game sessions or just while the player is playing? A simple autoID system would be to create a static int field that gives out the number to you objects, and everytime you get a number from that field increase it by one, that's all to get unique id's. If you need id's for every player's object then you might want to add some specific values to it, like the player name/id or some other important values.
     
  4. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Based on what?

    Is it enough to just keep track of an integer and increment when each new thing gets created?
    Code (csharp):
    1.  
    2. static int id = 0;
    3. int thisId;
    4.  
    5. void Awake()
    6. {
    7.     thisId = id++;
    8. }
    9.  
     
  5. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    12,706
    A UnityEngine.Object's InstanceID is guaranteed to be unique across all objects in any given Unity editor session, but it's not guaranteed to be constant for the same object across different sessions.

    Guid.NewGuid().ToString() is an easy way to get a unique, serializable value without having to manage a static incrementer value.