Search code examples
c#unity-game-engineinstantiation

How set unique variable to prefab after instantiate with loop unity c#?


I want to set variable to my child prefab class ( ArchiveRow.cs ) for each prefab witch instantiate with foreach loop. I can instantiate child in their parent's transform and access to their class ( ArchiveRow.cs ) but all child in thier parent get same variable witch I don't want it !

    foreach (var item in channels)
    {
        GameObject thisParent = Instantiate(parent, transform) as GameObject;

        foreach (var item2 in collections)
        {
            Instantiate(child);
            child.transform.parent = thisParent.transform;

            ArchiveRow archiveRowComponent = child.GetComponentInChildren<ArchiveRow>();
            archiveRowComponent.archiveId = item2.collectionId;

        }
    }

my result with code of above is look like=>

    thisParent(1) ->
        child(1) ==> archiveId = 100
        child(2) ==> archiveId = 100
        ...

    thisParent(2)->
        child(1) ==> archiveId = 200
        child(2) ==> archiveId = 200
        ...

        ...

But I want set variable like =>

    thisParent(1) ->
        child(1) ==> archiveId = 100
        child(2) ==> archiveId = 150
        ...

    thisParent(2)->
        child(1) ==> archiveId = 200
        child(2) ==> archiveId = 250
        ...

        ...

Solution

  • the problem is likely references.

    So,

    foreach (var item2 in collections)
    {
        Instantiate(child);
        child.transform.parent = thisParent.transform;
    
        ArchiveRow archiveRowComponent = child.GetComponentInChildren<ArchiveRow>();
        var myid = item2.collectionId;
        archiveRowComponent.archiveId = myid;
    
    }
    

    should fix it.