1
\$\begingroup\$

So, I'm currently working on a game.

The objects are treated as prefabs, so every time it is instantiated, the position of the object must randomize.

public ObjectDisplay SpawnObject()
{
    Vector3 randomPosition = new Vector3(Random.Range(-2.5f, 2.5f), 7f);

    GameObject obj = Instantiate(objPrefab, randomPosition, Quaternion.identity, objCanvas);
    ObjectDisplay objDisplay = obj.GetComponent<ObjectDisplay>();

    return objDisplay;
}

The randomPosition is what is supposed to be changing the positions, but what happens is that the prefabs would continue to spawn from the middle of the screen. I've tried changing the position values but that didn't do much.

The code is seemingly fine, but it doesn't function the way it is supposed to. Any ideas?

\$\endgroup\$
3
  • 2
    \$\begingroup\$ Just looking at the code it should work, but there might be something else which interferes. Your Instantiate-call adds it to an object called "objCanvas". I assume that's an UI canvas? Those can be a bit unintuitive at times. Is there something on your canvas which might control the positions of its children? \$\endgroup\$
    – Philipp
    Mar 6, 2018 at 10:03
  • 1
    \$\begingroup\$ In the prefab's script, do you manipulate the transform's position? Maybe the Awake, Start or Update callbacks are setting the transform position on the center of the screen \$\endgroup\$
    – Leo
    Mar 6, 2018 at 11:01
  • \$\begingroup\$ Have you tried printing what the value of randomPosition is and the value of obj.transform.position in the SpawnObject function? It should be working as intended. \$\endgroup\$ Mar 6, 2018 at 13:57

1 Answer 1

2
\$\begingroup\$

Just use this form, it always works for me:

Vector3 randomPosition = new Vector3(Random.Range(-2.5f, 2.5f), 7f, 0f);
GameObject wordObj = GameObject.Instantiate(wordPrefab); //as GameObject;
wordObject.SetParent(parent);
wordObj.transform.position = randomPosition;

//etc.
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Note also that the asker wants the object to be a child of a parent object, which you should maintain. The most performant method would be to pass the parent transform in the Instantiate command. \$\endgroup\$ Mar 6, 2018 at 19:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .