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 C#, It is possible to access specified Instantiated object as a later stage?

Discussion in 'Scripting' started by psykick1, May 22, 2020.

  1. psykick1

    psykick1

    Joined:
    May 19, 2020
    Posts:
    61
    Hi everyone,

    Wondering if it possible to access specified instantiated object, not right after instantiating,

    for example I want to access enemy26, after enemy50 is already instantiated.

    I guess I should give the Instantiated object a special definition while Instantiationg , and then I can call it from it special definition.


    Thanks in advance.
     
  2. GrizzlyPunchGames

    GrizzlyPunchGames

    Joined:
    May 21, 2020
    Posts:
    11
    Hi,
    I think you should instantiate your all enemies into table, then call specific enemy from table;
    I would do something like that:

    Code (CSharp):
    1. Enemy[] enemies;
    2. ....
    3. Enemy _enemy = Instantiate(enemy);
    4. enemies[i]= _enemy;
    5. i++;
    6. ...
    7. enemies[26].ValueYouWantToChange= someValue;
     
  3. psykick1

    psykick1

    Joined:
    May 19, 2020
    Posts:
    61
    Make sense.

    Possible to change the[26] to some name of an object?
    I mean for quick find what I want, find by name or something.
     
  4. HypnotistDK

    HypnotistDK

    Joined:
    Feb 14, 2016
    Posts:
    15
    You could use a dictionary if you want a name to it
     
  5. psykick1

    psykick1

    Joined:
    May 19, 2020
    Posts:
    61
    Sorry, What is Dictionary?
     
  6. GrizzlyPunchGames

    GrizzlyPunchGames

    Joined:
    May 21, 2020
    Posts:
    11
    I would reccomend to go and check -> List-> Dictionary, its similar to 2 dimensional table where first row is position second is name, but objects are stacked in queue so if you remove one from list all objecto comming after will get their postion -1,
     
  7. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    Code (CSharp):
    1. Dictionary<string, GameObject> myDictionary = new Dictionary<string, GameObject>();
    2.  
    3. public void SomeMethod() {
    4.   // Let's instantiate Gary
    5.   GameObject instanceOfGary = Instantiate(GaryPrefab);
    6.  
    7.   // Let's store Gary for later usage:
    8.   myDictionary["Gary"] = instanceOfGary;
    9. }
    10.  
    11. public void ADifferentMethod() {
    12.   // Hey what happened to that Gary we created before? I need him
    13.   GameObject theGaryFromBefore = myDictionary["Gary"];
    14.  
    15.   // I never much liked Gary
    16.   Destroy(theGaryFromBefore);
    17. }
     
  8. psykick1

    psykick1

    Joined:
    May 19, 2020
    Posts:
    61
    This is very nice.
    Thank you.