- Home /
Trying to get a prefab to pop up at various spawn points
Hi. I'm completely new to Unity and sort of making it up as I go along. I've managed to stumble through all the problems I've had so far (mostly thanks to this forum), but this one has me completely stumped - mostly because it's so close to working, but there's a glitch that doesn't make sense to me.
I'm creating a top-down maze style game where 'collectables' appear at randomly selected spawn points. I've created a prefab of the collectable (called 'Conversation'), then created prefabs of all the possible spawn points (just as empty gameobjects), and then I've created a list with all this spawn points in. Next I've got the following code in a script called ConversationStarter which is attached to the player.
public GameObject[] availableSpawns
public GameObject Conversation;
private GameObject Spawn;;
// Use this for initialization
void Start () {
ChangeSpawn();
StartConversation();
}
// Select random spawn point from list and create it
public void ChangeSpawn() {
int randomSpawnIndex = Random.Range(0, availableSpawns.Length);
GameObject SpawnPoint = (GameObject)Instantiate(availableSpawns[randomSpawnIndex]);
}
// Create conversation prefab and locate at spawn point
public void StartConversation(){
Spawn = GameObject.FindWithTag ("Respawn");
Instantiate(Conversation,Spawn.transform.position,Spawn.transform.rotation);
This is supposed to pick a spawn point from the list as soon as the game starts and then instantiate the conversation prefab at that location. At this point it works fine, but the next bit is where it's gone weird.
In a second script (also attached to the player) I've got the following:
void OnTriggerEnter2D(Collider2D collider) {
if (collider.gameObject.CompareTag("Conversation"))
Listening(collider);
}
// When reaching conversation, add point, destroy conversation and spawn point, then create another
void Listening(Collider2D pointsCollider) {
points++;
Destroy (GameObject.FindWithTag ("Respawn"));
Destroy (pointsCollider.gameObject);
GetComponent<ConversationStarter>().ChangeSpawn();
GetComponent<ConversationStarter>().StartConversation();
}
With this I was trying to make it that when the player reaches the location, the conversation and the spawn point are destroyed and then the original subroutine runs again to select a new spawn point and instantiate the conversation again. And I thought I'd cracked it with this.
Unfortunately, when the player reaches it and they disappear, the conversation reappears for an instant in the same spot (therefore giving an unnecessary second point) before going to the second place. On top of this, the spawn point jumps to the second location, and from then on the two are out of sync.
Running the game frame by frame, there seems to be a single frame where the spawn point is at location 2, but in the next frame it jumps to location 3, whilst the conversation is now at 2.
Any ideas what I've done wrong?