Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Instantiating objects inside objects

Discussion in 'Scripting' started by halejoy7, Jun 24, 2020.

  1. halejoy7


    Jun 24, 2020
    Hello, beginner here;

    I'm trying to instantiate several objects (spherical prefabs) within a transparent cube. The end result should look like the prefabs are embedded in the cube.

    The problem is that once I instantiate the prefabs, the cube moves. As far as I can tell, it moves so that one of the instantiated prefabs is at its centre. I don't understand why it does this, and I'm at a loss for how to stop it. If I add the prefab manually rather than by script, the problem doesn't appear.

    Notice that the cube is off-centre, with its centre (in the xy plane) at (1,1) rather than the original (0,0). The small dot is a sphere with coordinates (1,1,1).

    To try and stop this unwanted movement, I've disabled colliders on both the cube and the prefab, but to no effect.

    Here's the relevant section of my code:

    Code (CSharp):
    1.     public Transform Parent;
    2.     public GameObject spawnee;
    4.     void Start()
    5.     {
    6.         // Allocate position vector of new sphere
    7.         transform.position = new Vector3(1, 1, 1);
    8.         // Create sphere and set Cube as parent
    9.         GameObject sphere = Instantiate(spawnee,transform.position,Quaternion.identity);
    10.         sphere.transform.SetParent(Parent);
    11.     }
    Any suggestions that help me understand what's going on here and fix the issue will be most welcome!
  2. StarManta


    Oct 23, 2006
    It moves to (1,1,1) because you set its position to (1,1,1) on line 7.
    halejoy7 likes this.