- Home /
Change gameobjects position if it's already used by a different gameobject?
Gameobjects are getting randomly spawned on some platform objects. I want to avoid these two different gameobject to be spawned at the same exact location (money2 should change it's position).
Here is the code:
void Start()
{
int randMoney = Random.Range(0, 8);
Vector3 moneyPos = transform.position;
moneyPos.y += 0.5f;
if (randMoney < 1)
{
GameObject moneyInstance = Instantiate(money, moneyPos, money.transform.rotation);
moneyInstance.transform.SetParent(gameObject.transform);
}
int randMoney2 = Random.Range(0, 8);
Vector3 money2Pos = transform.position;
money2Pos.y += 0.5f;
if (randMoney2 < 1)
{
GameObject money2Instance = Instantiate(money2, money2Pos, money2.transform.rotation);
money2Instance.transform.SetParent(gameObject.transform);
}
if (money2Pos == moneyPos)
{
//where gameobject2s position should change
}
}
Thank you for taking your time!
Answer by jmhoubre · Dec 18, 2021 at 10:32 PM
In your code, money2Pos and moneyPos are always the same : transform.position is the position of the gameObject to which the script is attached.
if (money2Pos == moneyPos)
{
//where gameobject2s position should change
float radius = 2f;
Vector3 randomVector = Random.onUnitSphere * radius;
money2Pos += randomVector;
}
PS : Given the errors on the floats, you should test the distance between the two positions : if ((money2Pos - moneyPos).sqrMagnitude < 0.01f)
Your answer
Follow this Question
Related Questions
Transform a gameobject y rotation to another gameobject y rotation 1 Answer
Moving player to generated position 2 Answers
How to destroy a particular clone on touch/mouse? 1 Answer
How to mark the vertices on a mesh and make the markers follow them as you apply transformations 0 Answers
Move position with smoothing 0 Answers