Hello,
I am trying to spawn prefabs beneath the player using the following script(more explanation below the script):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class Spawn : MonoBehaviour
{
public float jumpForce;
public Transform SpawnPoint;
public GameObject Prefab;
public Transform player;
float timeCounter;
// Start is called before the first frame update
void Start()
{
}
IEnumerator waitSpawn()
{
yield return new WaitForSeconds(0.2921f);
Instantiate(Prefab, SpawnPoint.position, SpawnPoint.rotation).transform.parent = GameObject.Find("Player").transform;
}
// Update is called once per frame
void Update()
{
if (player.transform.position.y < 12f)
{
if (player.transform.position.y > -4f)
{
timeCounter += -1 * Time.deltaTime; //to set the time before player can touch screen again
if ((Input.touchCount > 0))
{
foreach (Touch touch in Input.touches) //so that it does not continue going up if screen is continuously touched
{
if (touch.phase == TouchPhase.Began && !(EventSystem.current.IsPointerOverGameObject(touch.fingerId)))
{
if (timeCounter < 0)
{
timeCounter = 0.29f; // Or whatever delay you want
GetComponent<Rigidbody>().AddRelativeForce(Vector3.up * jumpForce);
StartCoroutine(waitSpawn());
}
}
}
}
}
}
if (Input.GetMouseButtonDown(0))
{
if (timeCounter < 0)
{
timeCounter = 0.29f; // Or whatever delay you want
GetComponent<Rigidbody>().AddRelativeForce(Vector3.up * jumpForce);
StartCoroutine(waitSpawn());
}
}
}
I make the player jump using add force whenever the screen is tapped or the mouse is clicked so that the object does not spawn right under the player, causing it to glitch and fly really high, I also tried to add a pause before the player can spawn objects again, but this still happens sometimes.
I would appreciate if someone told me a way to fix this, code examples are greatly appreciated, I am a beginner so this way I can learn some more too. Thank You!