Search Unity

Spawning objects in only a certain area

Discussion in 'Scripting' started by Sugarmaster100, Jan 6, 2019.

  1. Sugarmaster100

    Sugarmaster100

    Joined:
    Nov 13, 2018
    Posts:
    40
    Hello,
    I would like objects to be spawned in a certain area when clicked, I have the code for spawning the "coins" and it works well.

    At the moment I can spawn a coin everywhere in the play space, I don't want that. is there any way to get the "coins" to spawn in only a certain area.

    Thanks

    Heres the code I got for spawning Coins
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class SpawnObj : MonoBehaviour
    6. {
    7.     public GameObject goldCoin;
    8.     public GameObject bronzeCoin;
    9.  
    10.     void Update()
    11.     {
    12.         if (Input.GetMouseButtonDown(0))
    13.         {
    14.             if (LOGIC.player == "yellow")
    15.             {
    16.                 Vector3 spawnPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    17.                 spawnPosition.z = 0.0f;
    18.                 GameObject objectInstance = Instantiate(goldCoin, spawnPosition, Quaternion.Euler(new Vector3(0, 0, 0)));
    19.                 LOGIC.turn++;
    20.             } else if (LOGIC.player == "red")
    21.             {
    22.                 Vector3 spawnPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    23.                 spawnPosition.z = 0.0f;
    24.                 GameObject objectInstance = Instantiate(bronzeCoin, spawnPosition, Quaternion.Euler(new Vector3(0, 0, 0)));
    25.                 LOGIC.turn++;
    26.             }
    27.         }
    28.     }
    29. }
    30.  
    31.  
     
  2. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    Hi @Sugarmaster100

    Well is it a side scroller, top down game or maybe something else?

    One way could be to use GameObjects with colliders.

    Colliders have bounds.

    You can take bounds min and max, and use these for random numbers to generate locations where to spawn items.

    Bounds have also Contains method.

    You can create a random point and see if it is contained in bounds.
     
  3. Sugarmaster100

    Sugarmaster100

    Joined:
    Nov 13, 2018
    Posts:
    40
    its a connect 4 esc game, i just want coins to be spawned above the board