Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Copy a reference and always point to the same as the original?

Discussion in 'Scripting' started by Shack_Man, Apr 25, 2019.

  1. Shack_Man

    Shack_Man

    Joined:
    Jun 7, 2017
    Posts:
    372
    In class A I am getting a reference to a class that is created and managed in another class, e.g. a SaveManager:

    Code (CSharp):
    1.  
    2. public class SaveManager : MonoBehaviour
    3. {
    4.             private SaveData saveData;
    5.  
    6. }
    7.  
    8. public class A
    9. {
    10.         private SaveData saveData;
    11.         saveData = FindObjectOfType<SaveManager>().saveData;
    12. }
    13.  
    Works perfect, both are referencing the same saveData class. But when I assign saveData to a new class, that reference is lost in class A, e.g. when loading a game

    Code (CSharp):
    1. public class SaveManager : MonoBehaviour
    2. {
    3.             private SaveData saveData;
    4.  
    5.              [...]
    6.  
    7.             string dataAsJson;
    8.             saveData = JsonUtility.FromJson<SaveData>(dataAsJson);
    9. }


    I know I could use a property in the Savemanager, and call that every time I want to access it in class A. But is there a simpler way, something like saying "I want saveData in class A to point to whatever saveData in class SaveManager points to"?
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    Basically, no.

    If you want your X to always point to the same object as my X, then instead of saving a reference to X, you should save a reference to the object that contains X, and always go through that object.

    In this case, instead of saving a reference to the SaveData, save a reference to the SaveManager. Either make SaveManager.saveData public, or add some function or property that returns it.
     
    Shack_Man and Joe-Censored like this.