Home > other >  Trying to make a a script that spawns that spawns a prefab object
Trying to make a a script that spawns that spawns a prefab object

Time:02-23

I have been trying to make a script that would drop prefabs at a random time in a random place in the y position so if anyone would be able to help me with this or tweak my code it would be greatly apprenticed

    using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RainSpawn : MonoBehaviour
{
      public GameObject myPrefab;
    
     public float timeBetweenSpawn;

   void update(){
     timeBetweenSpawn = 1 - Time.deltaTime; 
     Instantiate(myPrefab, transform.position   Random.insideUnitSphere * 5, Quaternion.identity);
   }

}

CodePudding user response:

Hmm, wow there is a lot of explaining here. Welcome to Unity... er, welcome to programming!

  • You need to have Update be capitalized for it to be recognized as the Unity update loop.

  • Also, you want to subtract Time.deltaTime from time between.. not from 1.

  • Also, you want to make sure timeBetween is initialized to non-zero, perhaps using Random.Range().

  • not sure what u mean by random place in the y position.. as you are using random position in a sphere,

Try this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RainSpawn : MonoBehaviour
{
      public GameObject myPrefab;
    
      public float minTime = 1f;
      public float maxTime = 5f;
      public float timeBetweenSpawn = 1f;

      void Start(){
        timeBetweenSpawn = Random.Range(minTime,maxTime);
      }

   void Update(){
     timeBetweenSpawn -= Time.deltaTime; 

     if(timeBetweenSpawn<0){
        Instantiate(myPrefab, transform.position   
             Random.insideUnitSphere * 5, Quaternion.identity);
         timeBetweenSpawn = Random.Range(minTime,maxTime);
     }
   }

}

  • Related