- Home /
Prefab Instantiation Creating Object At Origin
I am trying to instantiate a gameobject I have at a certain posititon, and all my code is correct but when I run the game, it creates the gameObject at origin. Here is the code below, I do not want to hardcode the spawn point in because I want to eventually change it.
Main Controller
void Start () {
GameObject CircleTroop = GameObject.FindGameObjectWithTag ("Circle Infantry");
Spawn spawnSystem = new Spawn();
spawnSystem.createTroop (CircleTroop, true);
}
Spawn Class
public class Spawn : MonoBehaviour {
private Vector3 playerSpawn;
private Vector3 AISpawn;
// Use this for initialization
public void Start () {
playerSpawn = GameObject.FindGameObjectWithTag ("Square Spawn").transform.position;
AISpawn = GameObject.FindGameObjectWithTag ("Circle Spawn").transform.position;
Debug.Log (AISpawn);
}
public void createTroop(GameObject troop, bool ai){
GameObject TroopSpawn = troop;
if (!ai) {
Instantiate (TroopSpawn, playerSpawn, Quaternion.identity);
} else {
Instantiate (TroopSpawn, AISpawn, Quaternion.identity);
}
}
}
I see you already have a debug.log for your AISpawn position. Is that correct or (0,0,0), and what about playerSpawn?
I put that there to see if it was grabbing the wrong vector3 quantity but those debugs both return the correct quantity
hmm, I don't see anything wrong with your code. Instantiate should spawn your objects at the given points...
You say you don't want to hardcode the spawnpoint in, but does it work correctly if you do that?
Answer by hbalint1 · Apr 30, 2015 at 10:23 PM
If i remember well, you cannot call a constructor on an object which was derived from Monobehaviour, because any method from Monobehaviour like start or update will be ignored. So basically any class that derived from Monobehaviour and use methods like those, need to be in scene. so put your spawn class on an empty gameobject and use gameobject.find for it. if you call the createTroop method on the found object, it should work.