Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Access script in another scene

Discussion in 'Scripting' started by RealLennen, Nov 29, 2023.

  1. RealLennen

    RealLennen

    Joined:
    Apr 22, 2022
    Posts:
    4
    Hello everyone,
    I am having a problem with getting an int value from one script in SceneA to a function in SceneB. My current solution is to create one GameObject in each scene, which holds a script, which then holds the int value. However, this always returns 0 in the function the int value is passed into.
    Thanks in advance.

    (If you think the problem is in my code, here it is)

    This is the script holding the value:
    Code (CSharp):
    1. public class GetInteger : MonoBehaviour
    2. {
    3.     public int myInt;
    4. }
    This is the script that changes the int (by pressing a button, this returns the correct value)
    Code (CSharp):
    1. public class LevelSelection : MonoBehaviour
    2. {
    3.     public GetMyInt getMyInt;
    4.     public int myInt;
    5.     public void OpenCharacterMenu(int myInt)
    6.     {
    7.         SceneManager.LoadScene("SceneB");
    8.         getMyInt.myInt = myInt;
    9.         Debug.Log(myInt);
    10.     }
    11. }
    And this is the function the int value is passed into (this returns the wrong value):
    Code (CSharp):
    1. public class SpawnManager : MonoBehaviour
    2. {
    3.     public GetInteger getMyInt;
    4.    
    5.     public void Start()
    6.     {
    7.         //Check if scene is active
    8.         if(SceneManager.GetActiveScene().name == "SceneB")
    9.         {
    10.             OnPlayActive();
    11.         }
    12.     }
    13.     public void OnPlayActive()
    14.     {
    15.         int myInt = getMyInt.myInt;
    16.         //This always returns 0.
    17.         Debug.Log(myInt);
    18.        
    19.     }
    20.  
    21. }
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,396
    Yes, because they're two completely different instances with no connection to one another in any way.

    If you want to transfer simple data around, then use a scriptable object.
     
  3. RealLennen

    RealLennen

    Joined:
    Apr 22, 2022
    Posts:
    4
    How do I do that? Can I just change MonoBehaviour to ScriptableObject or do I have to write an entirely new script?
     
  4. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,396
  5. RealLennen

    RealLennen

    Joined:
    Apr 22, 2022
    Posts:
    4
    Ok thank you