I wrote a script which pawns an object (instantiated prefab) each time the player touches the screen.
The maximum number of these spawned objects active in the scene at once is 3, and when they are not visible they will be destroyed. I need these prefabs to be able spawn again after they had been destroyed.
I tried this but it does not work...
This script is added to a game object called "canCreator" in my scene hierarchy:
public class CreatingCan: MonoBehaviour
{
public GameObject Can;
public int numberOfCans;
public bool canSpawn = true;
private void Start()
{
numberOfCans = 0;
}
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
Vector2 TouchPosition = Camera.main.ScreenToWorldPoint(touch.position);
if (touch.phase == TouchPhase.Began && canSpawn == true)
{
if (Instantiate(Can, TouchPosition, Quaternion.identity))
{
numberOfCans++;
}
}
}
if (numberOfCans >= 3)
{
canSpawn = false;
}
}
}
This script is on my can prefab:
public class fallingCan : MonoBehaviour
{
CreatingCan CC;
private void Update()
{
if (transform.position.x < Camera.main.transform.position.x - 10)
{
Destroy(gameObject);
CC.numberOfCans--;
}
}
}