- Home /
How can I translate my prefab on Instantiate?
I'm trying to spawn a prefab on a GUI Button click and put it in a specific position.
I can create the object but any attempts to position it after creation inside the onclick function do not work, it always stays at (0,0,0). Can someone please unlock the mystery as to why I can't re-position the prefab on creation? I've tried setting it manually, setting it via the Instantiate command, etc. Here's my code below.
using UnityEngine;
using System.Collections;
public class StartGame : MonoBehaviour {
GameObject [] tiles = new GameObject[1];
float speed = 1;
void OnGUI () {
// Make a background box
GUI.Box(new Rect(10,10,100,90), "Menu");
if(GUI.Button(new Rect(20,40,80,20), "Spawn")) {
tiles[0] = Instantiate(Resources.Load("tilePrefab")) as GameObject;
//tiles[0] = Instantiate(Resources.Load("tilePrefab"),
// new Vector3(-2,0,0),
// Quaternion.identity);
tiles[0].transform.position = new Vector3(-2,0,0);
}
}
Well that should work - have you got a script attached to the prefab that moves its position?
If it helps, the prefab is a drag-and-drop import of a Blender model that I exported to an fbx. I did this because I was having trouble with obj's and the ability to change the material/texture programmatically. There's nothing attached to the prefab other than the model. The script I pasted above is attached to an empty object that resides at (0,0,0).
Interesting note is that when I print the location to console right after the move, it does indeed print the correct location. If I move into the scene editor, select the prefab, and manually set the position to (-2,0,0) the object moves to the correct location. I was worried that maybe the unit of measurement differed between the editor and the script but I don't think that's the case either. With my luck, I'll find out that the is answer is something obvious and stupid but at least I'll have an answer.
Answer by MamaCatDev · Oct 11, 2012 at 12:06 AM
After a lot of frustration it seems that the problem was the model itself. I noticed an issue with the scaling of the model, so I went into blender and corrected it, then re-exported and suddenly it works. I changed none of the code at all.
So, until I figure out why exactly this happened, if anyone finds this question and thinks it may apply to them, make sure your scaling is normalized in Blender before you export.
Your answer
![](https://koobas.hobune.stream/wayback/20220613082033im_/https://answers.unity.com/themes/thub/images/avi.jpg)