Spawning Items
- BakdDev

- Feb 23, 2021
- 1 min read
I created three scripts called: SpawnPrize, AddForce, and AddPoints. Overall these scripts spawn new spheres, "prizes", and when they go down the chute a point is added to the score counter UI.
Using simple code, I can easily spawn as many spheres as needed. Firstly I create a reference to the prize prefab game object and declare a float integer to hold how many prizes have spawned so far. The 3rd variable I declare is a float named Radius, used to create the area where prizes will be allowed to spawn.
Creating a new function to hold random vector3 values, within a circle, then instantiate a prize prefab within. Within an if statement that checks the number of prize prefabs in the scene at the time, if the number is less than required we can use spawnPrize to spawn more.
public GameObject prizePrefab;
public int prizesSpawned;
public float Radius = 1;
void FixedUpdate()
{
if (prizesSpawned < 20)
{
Debug.Log("Spawing Prize");
spawnPrize();
prizesSpawned++;
}
}
void spawnPrize()
{
Vector3 randomPos = Random.insideUnitCircle * Radius;
Instantiate(prizePrefab, randomPos, Quaternion.identity);
}I declare an int named points, this is to hold how many points the player has whilst playing. I also create a reference to the UI text in the scene so I can update it from the script. So using an OnTriggerEnter within the script which is connected to a collider in the chute, when a prize prefab passes through it, the points variable goes up by one, the text is then updated separately.
public int points;
public Text pointsUI;
private void OnTriggerEnter(Collider other)
{
Debug.Log("Adding 1 point");
points++;
pointsUI.text = points.ToString();
}


Comments