How do I set a limit to the number of instantiations allowed on a prefab?

Hey all, I hope I am in the right place as this is my first time posting a question on here. I’m fairly new to C# and Unity.

So I am currently building a small prototype inspired by Pachinko. My game consists of a red ball prefab that on Input.GetMouseButtonDown(0) // Left mouse click…my red ball prefab is instantiated on mouse click and at mouse position, however…I only want to spawn a TOTAL of 30 balls (1 at a time on click). How would I go about doing this/setting a limit on my total number of balls available to use and then stop my mouse click instantiation once I’ve gone from having 30 balls to 0 balls.

I’d love a UI text that displays “Balls Left: 30” and counts down by one each time I click to spawn the ball prefab until it reaches 0 (Game Over).

I hope this makes sense! I am new to C#.

Here is my Spawn Manager Script:

public class SpawnManager : MonoBehaviour
{
// Variables

public GameObject ball;
[SerializeField] private GameObject ballPrefab;
private Vector3 mousePos;
public float xLimit = -40f;

void Start()
{

}

// Update is called once per frame

void Update()
{
SpawnPrefab();
}

public void SpawnPrefab()
{
// Left mouse click, spawn a ball on click
if (Input.GetMouseButtonDown(0))

{
mousePos = Input.mousePosition;
mousePos.z = 10;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
ball = Instantiate(ballPrefab, mousePos, Quaternion.identity) as GameObject;
}
}
}

CHEERS!! :smile:

Create a list of instantiated balls. When you go to instantiate a ball, first check the list.count. Only instantiate when list.count <= 30. When you instantiate a ball, you add it to the list.

If you want to do a balls left text, you just set it to: (30 - list.count).ToString().

1 Like

So I’m having trouble implementing your suggestions into my code. I have a list of 30 prefabs in the inspector but I can still click to spawn more than 30, an infinite amount actually

Can you post the current code please? Also, use CODE tags.
https://discussions.unity.com/t/481379

1 Like
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SpawnManager : MonoBehaviour
{
    // Variables

    public GameObject ball;
    [SerializeField] private GameObject ballPrefab;
    private Vector3 mousePos;
    public float xLimit = -65f;
    public List<GameObject> balls = new List<GameObject>();
    public Text ballsRemaining;

    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {
        if (balls.Count <= 30)
        {
            SpawnPrefab();
        }
                  
    }

    public void SpawnPrefab()
    {

        // Left mouse click, spawn a ball on click

        if (Input.GetMouseButtonDown(0))
           
        {

            mousePos = Input.mousePosition;
            mousePos.z = 10;

            mousePos = Camera.main.ScreenToWorldPoint(mousePos);
           
            ball = Instantiate(ballPrefab, mousePos, Quaternion.identity) as GameObject;

        }
    }
}

As you can see its a bit messy and I clearly have no clue what I’m doing with Lists lol but thank you for helping me out with this, sorry if I dont understand right away I am fairly new to coding

As far as I can tell without testing your code for real, you just forgot to add the ball in the balls list. So on the 48th line you need a balls.Add(ball);

BTW, your logic is strange, I would do something like this, better separation of concerns and you can use the SpawnPrefab method spawning objects at a location without the mouse in the future, if needed.

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SpawnManager : MonoBehaviour
{
    // Variables
    [SerializeField] private GameObject ballPrefab;
    [SerializeField] private int numberOfSpawns;
    public float xLimit = -65f;
    public List<GameObject> balls = new List<GameObject>();
    public Text ballsRemaining;

    void Update()
    {
        if (Input.GetMouseButtonDown(0) && balls.Count < numberOfSpawns)
        {
            var mousePos = Input.mousePosition;
            mousePos.z = 10;
            mousePos = Camera.main.ScreenToWorldPoint(mousePos);
      
            SpawnPrefab(mousePos);
        }
    }

    public void SpawnPrefab(Vector3 position)
    {
        var ball = Instantiate(ballPrefab, position, Quaternion.identity) as GameObject;
        balls.Add(ball);
    }
}
2 Likes
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SpawnManager : MonoBehaviour
{
    // Variables

    public GameObject ball;
    [SerializeField] private GameObject ballPrefab;
    [SerializeField] private int numberOfSpawns = 35;
    private Vector3 mousePos;
    public float xLimit = -65f;
    public List<GameObject> balls = new List<GameObject>();
    public Text ballsRemaining;
    public GameObject gameOverPanel;
    public bool isGameActive;

    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (balls.Count < numberOfSpawns)
        {
            SpawnPrefab();
        }
                 
    }

    public void SpawnPrefab()
    {

      
      
        // Left mouse click, spawn a ball on click

        if (Input.GetMouseButtonDown(0))
          
        {
          

            mousePos = Input.mousePosition;
            mousePos.z = 10;

            mousePos = Camera.main.ScreenToWorldPoint(mousePos);
          
            ball = Instantiate(ballPrefab, mousePos, Quaternion.identity) as GameObject;
            balls.Add(ball);
        }
    }
}

So I implemented most what you suggested, and man thank you so much for you help. I’ve been on this for quite a few days now. And yeah lol sorry about my weird logic, trying to get better with that. I’m currently going through Unity’s Junior Programmer bootcamp.

My next question is…Any idea how I can get my “Balls Remaining: 35” text to -1 from the 35 total each time I click to spawn a ball?

1 Like

You have the ballsRemaining reference to the Text object, it has a .text property.
You can use the $"Balls Remaining: {<something>}" formula to construct your string where the <something> should be a calculation. Take your max balls and subtract the number of balls already spawned.

I will leave the concrete implementation up to you. You’re in a boot-camp after all, you need to practice. Don’t hesitate to ask questions if you will have any!

1 Like

Basically the same way I said before. Try adding this line right after line 55.

ballsRemaining.text = "Balls Remaining: " + (numberOfSpawns - balls.Count).ToString();

Alright awesome! ill try my best to figure that out! Thanks for that, I definitely need the practice :smile:

So sorry that I missed this in your previous answer! Thank you so much this worked perfectly, exactly what I needed. Such a dope community here, thanks a lot to you both for your help! @Joe-Censored and @ you guys rock

2 Likes