I have 2 scripts about spawning terrain and fences infinitely when the invisible cubes touch the player. but when the player touch the invisible cubes, it did not spawn infinitely.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cubescript : MonoBehaviour
{
// Start is called before the first frame update
public GameObject track;
void Start()
{
}
// Update is called once per frame
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("Morelines"))
{
Instantiate(track, new Vector3(-204f, -39.40112f, 909f), Quaternion.identity);
}
}
}
This is my new cube script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Newcubescript : MonoBehaviour
{
// Start is called before the first frame update
public GameObject fence;
void Start()
{
}
// Update is called once per frame
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("Morelines"))
{
Instantiate(fence, new Vector3(-317f, 25.40112f, 625f), Quaternion.identity);
}
}
}
If you want the object to spawn infinitely while the player is touching the cubes, using OnCollisionStay should give you the result you want, you’ll probably want to put some kind of delay on the spawning of objects this way though as spawning an object every frame will most likely cause slow down
OnCollisionStay will be called every frame that they intersect, so if you want Instantiate to be called less often then you could add another condition before CompareTag.
To run every other frame, you could use this to check if the frameCount is an even number:
int interval = 2; // frames
if (Time.frameCount % interval == 0)
// Instantiate
Set interval to 3 to run once every three frames, etc.
However, this will cause the game to spawn more objects when running at a higher framerate.
That also doesn’t guarantee that Instantiate will be called on the first frame that they intersect.
This script still isn’t completely framerate-independent, but it should spawn about the same number of objects over time while still restricting the number of Instantiate calls to one per frame. If the framerate is too low (i.e. Time.deltaTime is greater than interval) then it won’t spawn as many objects.
If you need the same behaviour at any framerate, then use this to instantiate multiple objects if timer is over twice the value of interval.
int frames = Mathf.FloorToInt(timer/interval);
for (int i = 0; i < frames; i++)
{
//Instantiate
timer -= interval;
}
You could also use InstantiateAsync if your version of the engine supports it.