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

accessing a gameobject in different scene

Discussion in 'Scripting' started by hoshyargames, May 2, 2021.

  1. hoshyargames

    hoshyargames

    Joined:
    May 2, 2021
    Posts:
    24
    within a class there are reference to gameobjects in the scene A,

    the same gameobjects are available in the scene B.

    i have dragged the gameobjects in scene A into inspector fields. now how to reference these gameobjects in the scene B via script into relevant fields in the inspector?

    please give me some idea. thanls.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,517
    When you use multiple scenes you need to dynamically locate the other resources in the other scene via some mechanism.

    Your code must also be tolerant of other objects not being immediately ready, as all scene loading completes at the end of the current frame.

    Locator patterns that can work to notify consumers of later-added resources include:

    - singleton

    - FindObjectOfType<T>()

    - static mailbox

    - other less-reliable forms of Find() type mechanisms (name, tag, etc.)

    etc.

    The actual process is remarkably simple, but of course the devil is in the details and the timing.

    As with ALL new technology and techniques, DO NOT integrate this into your actual game first.

    Instead start a fresh small scene with a test locator script on it, and load a second scene that contains the desired object.

    Work with only those two parts and PLENTY of Debug.Log() statements scattered everywhere until you fully understand what is involved.
     
    Last edited: May 2, 2021
  3. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    Unless you mean that you loaded scene A first and set the objects to DontDestroyOnLoad (in which case you already have references to them), then the objects in scene B are not "the same" objects. They might be similar objects, but that doesn't help you get a reference to them (at least not directly).

    The typical way to obtain a reference at runtime is to use one of the "Find" functions, like GameObject.Find, Transform.Find, FindObjectsOfType, etc.

    You can also copy a reference from some other variable, but if the variable is just located on another GameObject then you still need a reference to that object. You can possibly get around this using static variables.
     
    hoshyargames likes this.
  4. hoshyargames

    hoshyargames

    Joined:
    May 2, 2021
    Posts:
    24
    i did as you said and also the other friend above said. but the problem is in the second scene , because the game objects are diable , singleton dont find them . and when i click and game objects are displayed, referencing do not occur.

    what i do to fix it?

    here is code:

    Code (CSharp):
    1. public class AudioManager : MonoBehaviour
    2. {
    3.     private static AudioManager instance = null;
    4.  
    5.     public static AudioManager Instance
    6.     {
    7.         get { return instance; }
    8.     }
    9.  
    10.     [SerializeField]
    11.     private AudioMixer audioMixer;
    12.  
    13.     public Image musicOnIcon;
    14.     public Image musicOffIcon;
    15.  
    16.     public Image sfxOnIcon;
    17.     public Image sfxOffIcon;
    18.  
    19.     private bool _musicIsMuted = false;
    20.     private bool _sfxIsMuted = false;
    21.  
    22.     private const string MUSIC_PREFS_KEY = "musicmuted";
    23.     private const string SFX_PREFS_KEY = "sfxmuted";
    24.  
    25.     private const string AUDIO_MIXER_MUSIC = "music";
    26.     private const string AUDIO_MIXER_SFX = "sfx";
    27.  
    28.     private const int MUTED = 1;
    29.     private const int NOT_MUTED = 0;
    30.  
    31.     private const float MUTED_VALUE = -80f;
    32.     private const float NOT_MUTED_VALUE = 0f;
    33.  
    34.  
    35.  
    36.     private void Awake()
    37.     {
    38.         if (instance != null && instance != this)
    39.         {
    40.             Destroy(this.gameObject);
    41.             return;
    42.         }
    43.         else
    44.         {
    45.             instance = this;
    46.         }
    47.  
    48.         DontDestroyOnLoad(this.gameObject);
    49.     }
    50.  
    51.     private void Start()
    52.     {
    53.         musicOnIcon = GameObject.Find("on_musics").GetComponent<Image>();
    54.         musicOffIcon = GameObject.Find("off_musics").GetComponent<Image>();
    55.  
    56.         sfxOnIcon = GameObject.Find("on_sfx").GetComponent<Image>();
    57.         sfxOffIcon = GameObject.Find("off_sfx").GetComponent<Image>();
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,517
    Back up as I noted above and start with two simple scenes.

    You problem indicates that you have not understood the lifetime scope and timing of things appearing, disappearing, lingering, don't destroy, and generally how unrelated unconnected items in a Unity game successfully locate each other.

    You have GOT to understand this fully before you even begin to attempt it within your actual game.

    To do otherwise is just going to waste your time, confuse you with the extra complexity of your game, and possibly even damage other parts of your codebase as you experiment.

    You must get practical hands-on experience with the multi-scene timing or you will not be able to reason about your issue.

    ALSO: anyone reasoning about your script here in a vacuum probably cannot help, as it is intimately tied to timing and the particular way you load the scenes: additively? sequentially? some with a singleton? something else? The possibilities are limitless and you need to be able to reason about them.
     
    SemanticDuck, X3doll and S1NERGY like this.
  6. hoshyargames

    hoshyargames

    Joined:
    May 2, 2021
    Posts:
    24
    i made in scene B the parent object active , but again also , it is not found . why?
     
  7. hoshyargames

    hoshyargames

    Joined:
    May 2, 2021
    Posts:
    24
    so how is possible that singleton can access a deactive gameobject in another scene? this gameobject is a child inside ui canvas by the way.

    i need a beginner help please.
     
  8. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,606
    What sort of information do you need from the other object? Is it just a variable/Value? Perhaps a Scriptable Object would be more straight forward.
     
    Kurt-Dekker and hoshyargames like this.
  9. hoshyargames

    hoshyargames

    Joined:
    May 2, 2021
    Posts:
    24

    it is like this:

    you bring your gameobject from scene a to scene b.

    in scene b , you have ui image which is deactive . but in your gameobject you have fields which need to be accessing that deactive ui image, how will you access that ui image?

    hope it is clear to you.

    by the way the gameobject which comes to scene b is a singleton.
     
  10. hoshyargames

    hoshyargames

    Joined:
    May 2, 2021
    Posts:
    24
    any idea please?
     
  11. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,517
    You can't just keep a UI Image. They need a canvas and all the other stuff they come with above them.

    My first reply offers three completely-reliable approaches to finding or tracking stuff. If you put it in the scene in the first place, keep a reference to it somewhere, such as with a GameManager. There thousands of GameManager tutorials on Youtube. Start there and make sure you take the time for Step #2 below:

    Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

    How to do tutorials properly, two (2) simple steps to success:

    Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That's how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.

    Fortunately this is the easiest part to get right: Be a robot. Don't make any mistakes.
    BE PERFECT IN EVERYTHING YOU DO HERE!!

    If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

    Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

    Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.


    Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there's an error, you will NEVER be the first guy to find it.

    Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!