Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Am I using GetComponent<> correctly?

Discussion in 'Scripting' started by RDG_Admin, Mar 23, 2021.

  1. RDG_Admin

    RDG_Admin

    Joined:
    Oct 4, 2014
    Posts:
    22
    Simple enough, I'm trying to use a string from another script and using Debug.Log() I've found the issue to be using GetComponent and I'm wondering if somebody can take a look at my issue.

    Script #1 (DemoScript)
    Code (CSharp):
    1. public string String1;
    2.  
    3. void Start()
    4. {
    5.     String1 = transform.parent.name;
    6.     Debug.Log(String1);
    7. }
    Debug.Log returns the string no issues.

    The second script where I'm trying to call the string is where I'm running into problems.

    Script #2
    Code (CSharp):
    1. void Start()
    2. {
    3.     string String2 = GetComponent<DemoScript>().String1;
    4.     Debug.Log("This is another script trying to call " + String2);
    5. }
    Nothing shows in Debug.Log for this, but no errors are shown either. I've looked at other places and apparently this is the correct way to do it but I can't get it working. Any help would be appreciated
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,992
  3. RDG_Admin

    RDG_Admin

    Joined:
    Oct 4, 2014
    Posts:
    22
  4. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Are you seeing the 1st Debug.Log before or after the 2nd? Are you setting String1 anywhere else?
     
  5. RDG_Admin

    RDG_Admin

    Joined:
    Oct 4, 2014
    Posts:
    22
    The first Debug.Log is working - this was to see the string was working. Nothing in the second string with the GetComponent is working.
     
    Last edited: Mar 23, 2021
  6. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    But what order do they appear in the Console?
     
  7. CMDR_Garbage

    CMDR_Garbage

    Joined:
    Apr 29, 2019
    Posts:
    22
    It's probably because they're both in the start, if you put
    Code (CSharp):
    1. String1 = transform.parent.name;
    2.     Debug.Log(String1);
    in
    Code (CSharp):
    1.  private void Awake()
    2.     {
    3. String1 = transform.parent.name;
    4.     Debug.Log(String1);
    5. }
    instead it'll probably work fine.
     
  8. seejayjames

    seejayjames

    Joined:
    Jan 28, 2013
    Posts:
    685
    Use an Invoke() with a slight delay in your second script. The string isn't getting set in time for the other one to access it.