Instantiating a prefab as a child of an object I choose

How do i instantiate an object (like Instantiate(collector);) as a child of an object I set by declaring a variable (like var board : GameObject;)?

var myObject = Instantiate(collector);
myObject.transform.parent = board.transform;

–Eric

I thought I was doing it right…where am i wrong here? The object I want to parent is being generated by this function:

var collector : GameObject; 
var numPointsNeeded = 1; 
var board : GameObject;
function Start() { 
board = GameObject.Find("Board");
collector = GameObject.Find("Gem"); 
spawnitems(); 
} 

function spawnitems() { 
    var spawns = GameObject.FindGameObjectsWithTag("Respawn"); 

     Debug.Log(spawns.Length); 
    
    for (j=0;j<10;j++) { 
        var numLeftToTry = 10 - j; 
        var chance = numPointsNeeded /  numLeftToTry; 
        
        if (Random.value < chance) { 
            var thisSpawnPoint : GameObject = spawns[j]; 
            Instantiate(collector, thisSpawnPoint.transform.position, thisSpawnPoint.transform.rotation); 
            collector.transform.parent = board.transform;
numPointsNeeded--; 
        } 
    } 
}

When you instantiate “collector”, you’re not assigning the instance to a variable, so you can’t do anything with it. “collector.transform.parent” in your case refers to the prefab. Take a look at my code again. :slight_smile:

–Eric

Like this I think…

var collector : GameObject; 
var numPointsNeeded = 1; 
var board : GameObject;
function Start() { 
board = GameObject.Find("Board");
collector = GameObject.Find("Gem"); 
spawnitems(); 
} 

function spawnitems() { 
    var spawns = GameObject.FindGameObjectsWithTag("Respawn"); 

     Debug.Log(spawns.Length); 
    
    for (j=0;j<10;j++) { 
        var numLeftToTry = 10 - j; 
        var chance = numPointsNeeded /  numLeftToTry; 
        
        if (Random.value < chance) { 
            var thisSpawnPoint : GameObject = spawns[j]; 
            var thisObj = Instantiate(collector, thisSpawnPoint.transform.position, thisSpawnPoint.transform.rotation); 
            thisObj.transform.parent = board.transform;
numPointsNeeded--; 
        } 
    } 
}