Search Unity

What is good approach to get reference of variable?

Discussion in 'Editor & General Support' started by leegod, Feb 20, 2017.

  1. leegod

    leegod

    Joined:
    May 5, 2010
    Posts:
    2,476
    So there are many times that I need to get reference of various gameobjects in hierarchy.

    For example, to manipulating UI, turn it on/off, I normally use gameObject.SetActive(true/false).

    Then we need to get reference of that gameobject at code.

    How do you do this normally and what is good method?

    I uses normally make the variable public and drag Hierarchy's target gameobject and drop this to variable.

    But unity is very fragile and there are many times that Scene file itself being crashed or all things inside hierarchy just being disappeared.

    Then, at Start or Awake part in script, using GameObject.Find("Name") is more good way for get reference?

    or another way?

    Thanks.
     
  2. andymads

    andymads

    Joined:
    Jun 16, 2011
    Posts:
    1,614
    I've not had problems doing this. I usually make my fields private and use the [SerializeField] attribute instead of making them public.
     
  3. leegod

    leegod

    Joined:
    May 5, 2010
    Posts:
    2,476
    Any benefit of doing that? So can block unexpected change from other script?

    So you make it SerializeField and drag hierarchy's object to there?
     
  4. andymads

    andymads

    Joined:
    Jun 16, 2011
    Posts:
    1,614
    Yes and yes.
     
  5. leegod

    leegod

    Joined:
    May 5, 2010
    Posts:
    2,476
    Then how handle situation of scene crash?
    And after made a prefab, prefab can't preserve scene object registered variable.(become null)
     
  6. andymads

    andymads

    Joined:
    Jun 16, 2011
    Posts:
    1,614
    What's a scene crash?

    We have several projects, some that are a few years old. We don't have a problem with wired up references disappearing.
     
  7. leegod

    leegod

    Joined:
    May 5, 2010
    Posts:
    2,476
    Stored in external SSD, worked well in one computer, but when move computer, suddenly file crashes and scene file become 1kb, and not opened.
     
  8. andymads

    andymads

    Joined:
    Jun 16, 2011
    Posts:
    1,614
    We've never experienced this. We store our projects (only Assets and ProjectSettings folders) on SVN repositories and occasionally check out to new computers and it all works fine.
     
  9. leegod

    leegod

    Joined:
    May 5, 2010
    Posts:
    2,476
    My project size is over 22 giga. Can you recommend SVN?
     
  10. andymads

    andymads

    Joined:
    Jun 16, 2011
    Posts:
    1,614
    We don't have experience with projects that size. Our biggest project is around 1Gb.