Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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!

What I have tried:

if (money2Pos == moneyPos)
        {
            //where gameobject2s position should change
        }
Posted
Updated 18-Dec-21 6:56am

1 solution

I have used unity a little bit. So take this with a grain of salt.

You are only instantiating an object when your random number is 0, in both cases.

How many object will be created at one time. will you have up to 15 objects or only the two? If you have 15, it might be worth while to create a list of gameobjects and loop through them to find matches. Or you might want to have a set of dedicated spawn locations and fill those as you spawn objects. You could randomize the spawn location to give a bit of randomness.

Also it looks like your comparison on money2Pos and moneyPos will fail if any of the x,y, or z's don't match between the two. Your z could be slightly off but still in the same x,y and appear to be in the same position.

Again, this is just looking at the logic in your code. I may be way off base here, but it is some thoughts to look at.

Ron
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900