samedi 26 décembre 2015

How to Spawn Two Different Objects Randomly in Two Specified Positions in Unity 2D?

I am working on a 2D project and I am trying to instantiate two different objects using two different positions that are already specified in the code. Each object should pick one random value of the two positions. So each time the player runs the game, the objects can exchange their positions. My problem is that sometimes the two objects pick the same exact position, which is wrong. The followings are the only two possibilities that should work in the game:

Possibility 1: 1

Possibility 2: 2

This is the code I am using:

using UnityEngine;
using System.Collections;

public class Randomizer : MonoBehaviour
{

    public GameObject[] prefab;
    int prefab_num;
    Vector3[] positions;
    Vector3 pos1;
    Vector3 pos2;

    void Start(){ 
        prefab_num = Random.Range(0,1);
        positions = new Vector3[]{new Vector3 (-5, 0f, 0f), new Vector3 (5, 0f, 0f)};
        pos1 = positions [Random.Range (0, positions.Length)];
        pos2 = positions [Random.Range (0, positions.Length)];
        Instantiate (prefab [0], pos1, Quaternion.identity);
        Instantiate (prefab [1], pos2, Quaternion.identity);

    }

    void Update(){ // Here I am trying to prevent objects from spawning on each other but it didn't work for me
        if (pos1 == positions [0] && pos2 == positions [0]) {
            prefab [prefab_num].transform.position = positions [1];
        } else if (pos1 == positions [1] && pos2 == positions [1]) {
            prefab [prefab_num].transform.position = positions [0];
        }
    }       
}




Aucun commentaire:

Enregistrer un commentaire