- Home /
How do I teleport one Object to an emptyGameObject?
Instead of Destroy(gameObject) I want place a new location to it to 3 random emptyObject in the scene. so far i have this:
void SpawnMonster(){
int spawnIndex = Random.Range (0, spawnPointList.Length);
//Instantiate (monster, spawnPointList [spawnIndex].position, spawnPointList [spawnIndex].rotation);
point = Vector3 (Random.Range ();
monster.transform.position = point;
}
Any help will be appreciated. And sorry for the bad english.
Answer by apple92 · May 28, 2015 at 08:20 AM
If you have your emptyObject's in the spawnPointList, then just use spawnIndex to access the GameObject stored in that entry and get it's position and rotation:
void SpawnMonster(){
int spawnIndex = Random.Range (0, spawnPointList.Length-1);
monster.transform.position = spawnPointList [spawnIndex].position;
monster.transform.rotation = spawnPointList [spawnIndex].rotation;
}
If you don't have the empty GameObjects in the List/Array already, then there are multiple ways of indexing them. Either by tagging them with something like "monsterSpawn" and then use GameObject.FindGameObjectsWithTag (see here) or use a public List/Array and drag&drop them in the Inspector. There are more ways of doing it, but those two are pretty easy to do.
Also note that if you use the spawnPontList.Length, you could get an Index Out Of Range Exception. If there are 3 Items in your List, Random.Range(0, spawnPointList.Length) would return a Number between 0 and 3. The third Item in the Array/List however would have the index 2, because Lists and Arrays start at 0 with indexing. Instead, use Random.Range(0, spawnPointList.Length-1) to get the Range right.
Your answer
Follow this Question
Related Questions
Collision for Amount of Time 1 Answer
Teleporting a character to mouse position 1 Answer
Portal between scenes? 3 Answers
2d game Teleporter works only as a single instance 1 Answer
FPSContoller Teleportation Script is blocking somehow 2 Answers