Reputation: 133
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];
}
}
}
Upvotes: 0
Views: 2602
Reputation: 3629
Assuming we first assign the position of the first object, then the position of the second object, then there is only one random factor: the positions themselves. So one Randomization is enough.
void Start()
{
int firstPosIdx = Random.Range(0, 1);
Vector2 firstPos = positions[firstPosIdx];
Vector2 secondPos = positions[1 - firstPosIdx];
// instantiate object 1 at firstPos, object 2 as secondPos
}
Upvotes: 1
Reputation: 3327
Once you find pos1
, you already know that pos2
is whatever pos1
wasn't.
public void Start()
{
int prefab_num = Random.Range(0, 1);
Vector2 positions = new Vector2[] { new Vector2(-5, 0), new Vector2 (5, 0) };
Vector2 pos1 = positions[Random.Range(0, positions.Length)];
Vector2 pos2 = positions.IndexOf(pos1) == 0 ? 1 : 0;
// Instantiate here
}
A few other things to note.
Vector2
is a Vector3
who's z
is 0, so it can be used when z
is 0.
Update
is being called every frame, but what you're doing is just a one time check. A better way to do this approach is to change your Start
to Awake
, and your Update
to Start
.
This way, you can get the positions and instantiate the, then check to prevent overlap in Start
and leave nothing on the Update
.
Upvotes: 0