So Im trying to make Snake and I want to instantiate a food object within my bounds. currently I can do that but it keeps creating new objects and doesn’t stop. this is because its in the update function and I don’t have any code that stops it. My idea is to instantiate a single object in Start() and then use OnTriggerEnter2D() to detect if the object is destroyed and then instantiate new objects in a similar fashion.
Here is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Food : MonoBehaviour
{
private Vector3 screenBounds;
private Vector2 randomRange;
public GameObject food;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
randomRange = new Vector2(Random.Range(-screenBounds.x, screenBounds.x), Random.Range(-screenBounds.y, screenBounds.y));
Instantiate(food, randomRange, Quaternion.identity);
}
private void OnTriggerEnter2D(Collider2D col)
{
if(col.tag == "Player")
{
Instantiate(food, randomRange, Quaternion.identity);
}
}
}
Please Help
Thanks