- Home /
How to clone a simple GameObject where specified.
I am a new game programmer to Unity. I am currently trying to clone a single Transform
called StoneBlock. The original StoneBlock exists in the Scene already. How would I clone this block and put it where the parameters specify and leave the original in its place?
I have attempted to do this using GameObject.Instantiate()
, but it gives me errors saying:
BCE0005: Unknown identifier: 'StoneBlock'.
Here is my code of my custom World
class:
public static class World {
final var blocks : int = 1;
final var blockSizeX : float = 2.5f;
final var blockSizeY : float = 2.5f;
final var blockSizeZ : float = 2.5f;
public static function addBlock(blockId, x, y, z) {
var xp : float = x;
var yp : float = y;
var zp : float = z;
if (blockId == 1) {
var prefab = GameObject.Instantiate(StoneBlock.transform, Vector3(xp * blockSizeX, yp * blockSizeY, zp * blockSizeZ), StoneBlock.transform.rotation).gameObject;
//Instantiate(prefab, Vector3(xp * blockSizeX, yp * blockSizeY, zp * blockSizeZ), Quaternion.identity);
}
}
}
What am I doing wrong?
Answer by rutter · Dec 06, 2013 at 09:22 PM
Important distinction: the compiler is looking for a variable in your code, not an object in the scene. There very well might be a GameObject named "StoneBlock", but the scripting engine won't know that unless you give it the information.
As an example:
//look up object at runtime
Transform StoneBlock = GameObject.Find("StoneBlock").transform;
Or, you could use the inspector:
//inspector var
public Transform StoneBlock;
//later, in some function like Update():
Transform clone = Instantiate(StoneBlock);
There are quite a few functions that help you find and manipulate objects in the scene. Generally you'll want to find a GameObject (Find, FindByTag, collision events, etc.) or some component attached to a GameObject (GetComponent, GetComponentInChildren, etc.)