c# script not able to set prefab as child of object.
I think I am to stupid or something, I have a hard time getting some prefabs to be children of other prefabs through a C# script.
I have some prefabs of some platforms, but I did not want all the platforms to look a like. I thefor made some empty game objects children of the platforms. The Idea was to randomly spawn grass in those gameobjects.... And that does work nicely. But the platforms are floating up and down, and I therfor need the grass to instantiate as children of the platforms.
My first code, that is attached to to the platform looks like this:
public Transform[] prefabSpawns;
public GameObject prefabGrass;
void Start () {
Spawn();
}
void Spawn()
{
for (int i = 0; i < prefabSpawns.Length; i++)
{
int coinFlip = Random.Range (0, 100);
if (coinFlip < 70)
{ Instantiate(prefabGrass, prefabSpawns[i].position, Quaternion.identity);
}
}
}
And that did work very well, a side from the grass not being children of the platforms. I then followed the answer from this thread Answer the code now looks like this:
public Transform[] prefabSpawns;
public GameObject prefabGrass;
void Start () {
Spawn();
}
void Spawn()
{
for (int i = 0; i < prefabSpawns.Length; i++)
{
int coinFlip = Random.Range (0, 100);
if (coinFlip < 70)
{var NEWpreFabGrass = Instantiate(prefabGrass, prefabSpawns[i].position, Quaternion.identity);
NEWpreFabGrass.transform.parent = gameObject.transform;
}
}
}
But now i just get an error saying "Assets/Scripts/smallPlatformPrefabSpawn.cs(24,48): error CS1061: Type UnityEngine.Object' does not contain a definition for
transform' and no extension method transform' of type
UnityEngine.Object' could be found (are you missing a using directive or an assembly reference?)"
What am I doing wrong?
I know this was a long question, but I just wanted to make sure I asked it correctly.
Answer by andzq · Oct 14, 2016 at 11:15 PM
instead of your line 16:
var NEWpreFabGrass = Instantiate(prefabGrass, prefabSpawns[i].position, Quaternion.identity);
try:
GameObject NEWpreFabGrass = Instantiate(prefabGrass, prefabSpawns[i].position, Quaternion.identity) as GameObject;
besides this one line I did not change anything and your code runs without any trouble (: