- Home /
Instantiate Terrain Object as child of Empty Game Object
I realise this has been asked many times already, but I've just come from FOUR other threads with similar titles, tried what they said, and couldn't get it to work.
I have a script attached to an empty Game Object (with box collider attached). I want to instantiate a terrain piece as a child of the object.
So far I have:
var tile;
tile = Instantiate (fHigh1, Vector3(r, 0, c), transform.rotation);
tile.transform.parent = this;
A multitude of different errors pop up with every combination I try. I've also tried:
tile.transform.parent = transform;
tile.transform.parent = Transform;
tile.Transform.parent = transform;
tile.Transform.parent = Transform;
tile.transform.this = transform;
Help please :(
Answer by fafase · Jan 31, 2013 at 08:26 AM
I would think your error is there:
tile.transform.parent = this;
'this' represents the script not the object.
try
tile.transform.parent = transform;
The code below works for me (in C#):
public class Script : MonoBehaviour {
public GameObject tile;
void Start () {
GameObject obj = (GameObject)Instantiate(tile,new Vector3(0,0,0),Quaternion.identity);
obj.transform.parent =transform;
}
}
Note: Since you are using UnityScript, if you have #pragma strict
at the top var tile;
should be var tile:GameObject;
var tile : GameObject ;
tile = Instantiate (fHigh1, Vector3(r, 0, c), transform.rotation);
Throws error: "BCE0022: Cannot convert 'UnityEngine.Transform' to 'UnityEngine.GameObject'."
And as you read above, I already tried:
tile.transform.parent = transform;
With no success. :( Perhaps it is in fact:
tile.transform.parent = transform;
but I have to fix the other issue first?
You may have different type of variables, so to make it simple just make them all GameObject:
var obj:GameObject;
var tile:GameObject;
function Start () {
tile = Instantiate(obj,Vector3(0,0,0),Quaternion.identity);
tile.transform.parent =transform;
}
I did what you said and played:
InvalidCastException: Cannot cast from source type to destination type. tileCollider.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/tileCollider.js:57)
:(
A preview:
var tile : GameObject; var fHigh1 : GameObject;
function OnTriggerEnter ( other : Collider )
{
r = other.transform.position.x;
c = other.transform.position.z;
if ( other.gameObject.name == "fHigh1")
{
tile = Instantiate (fHigh1, Vector3(r, 0, c), Quaternion.identity);
}
tile.transform.parent = transform;
}
Note the other.gameObject.name is referring to a DIFFERENT "fHigh1" object.
Your answer
Follow this Question
Related Questions
Creating new Transform from existing objects Transform to Instantiate object 1 Answer
Getting instance of an sub object rather than the original's subobject 0 Answers
Instantiate a Prefab as child 0 Answers
Instantiate prefab as Child to remove and re-do later 2 Answers
Instantiated GameObject collision without script repetition? 1 Answer