Randomly place a cube near to the movable object

Hello!

I got a movable object. In the Object’s hierarchy it has empty game object called Spawner. I want it to place a small cube near to object randomly when space bar is pressed:

   void Update()
   {
       if (Input.GetKeyDown(KeyCode.Space))
       {
           float distanceToCurrent = Vector3.Distance(targetObject.transform.position, transform.position);

           if (distanceToCurrent <= 6)
           {

               //Instantiate cube randomly
               int cubePointX = Random.Range(-10, 70);
               int cubePointY = Random.Range(-10, 70);

               Vector3 cubePos = new Vector3(cubePointX, 1, cubePointY);
               Instantiate(cubePrefab, cubePos, Quaternion.identity);
           }
       }
   }

I played with Random.Range 's coordinates to fulfill my need for awhile since I couldn’t resolved it.

Any idea would be gladly appreciated…

You need to instantiate the object as a child of the target object, and then set its local position. In your case it’d be something like this (assuming you have a reference to the target object called spawner):

GameObject newCube = Instantiate(cubePrefab, spawner.transform);
newCube.transform.localPosition = cubePos;

1 Like
  void Update()
   {
       if (Input.GetKeyDown(KeyCode.Space))
       {
           float distanceToCurrent = Vector3.Distance(targetObject.transform.position, transform.position);

           if (distanceToCurrent <= 6)
           {

               //Instantiate cube randomly
               int cubePointX = Random.Range(-10, 70);
               int cubePointY = Random.Range(-10, 70);

               Vector3 cubePos = new Vector3(cubePointX + targetObject.transform.position.x, 1, cubePointY + targetObject.transform.position.y);
               Instantiate(cubePrefab, cubePos, Quaternion.identity);
           }
       }
   }

should work.

1 Like

ZY_bros sorry, it doesn’t work…

Thank you all…

Strange, but alr.

Excuse me… it’s my fault… Thanks so much…

No prob.
Good luck game deving!

1 Like