I want to create sprites that fall from random top positions or x and y. I have created a square object I mean sprite and add this code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomFall : MonoBehaviour
{
public GameObject spritePrefab;
public float spawnInterval = 1f;
public float spawnRadius = 5f;
public float fallSpeed = 2f;
private float timer;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
timer += Time.deltaTime;
if(timer >= spawnInterval){
spawnSprite();
timer = 0f;
}
}
private void spawnSprite() {
float spawnX = Random.Range(-spawnRadius, spawnRadius);
float spawnY = transform.position.y + spawnRadius;
Vector3 spawnPosition = new Vector3(spawnX, spawnY, 0f);
GameObject sprite = Instantiate(spritePrefab, spawnPosition, Quaternion.identity);
Rigidbody2D rb = sprite.GetComponent<Rigidbody2D>();
rb.velocity = Vector2.down * fallSpeed;
}
}
I have added Rigidbody2D and yes it falls but onetime and one sprite. Where is the problem?