Search Unity

Accessing instantiated gameobjects

Discussion in 'Scripting' started by MathewHI, May 29, 2017.

  1. MathewHI

    MathewHI

    Joined:
    Mar 29, 2016
    Posts:
    501
    How can I access varDmodelInstance from a different script?

    //This is in a script called EnemySpawner

    public GameObject SetUpInstance()
    {

    GameObject varDmodelInstance = Instantiate (enemy, spawnPoint.position, spawnPoint.rotation) as GameObject;
    return varDmodelInstance;
    }
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Your EnemySpawner script:
    Code (csharp):
    1.  
    2. public GameObject varDmodelInstance;
    3. public GameObject SetUpInstance() {
    4.    varDmodelInstance = Instantiate (enemy, spawnPoint.position, spawnPoint.rotation) as GameObject;
    5.    return varDmodelInstance;
    6.    }
    7.  
    Your other script:
    Code (csharp):
    1.  
    2. EnemySpawner enemySpawner;
    3. // when you want the reference:
    4. enemySpawner.varDmodelInstance // etc..
    5.  
    That's one option :)
     
  3. MathewHI

    MathewHI

    Joined:
    Mar 29, 2016
    Posts:
    501
    Wouldn't I have to call SetUpInstance from the other script?
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Okay, that was something I was going to mention or add to my response. You could call that from your other script, yes, but you don't have to. The way I wrote, you'll have a reference to that variable in the first script, and you can also fetch the variable in the second script. However, something I couldn't tell from your post is in order to fetch that value (without calling it from the other script), you'd have to have called it at least once in the first script*.
    If it's the second script that needs to call it, then you can do that, also or instead! :)
    Then, also, if you need to call it only if it's not been called or something like that, you could call it if the variable is null (only)..Hope that makes sense.
    Expand your question if you need more info :)
     
  5. MathewHI

    MathewHI

    Joined:
    Mar 29, 2016
    Posts:
    501
    ok thanks for help.