How do i get prefabs to randomly instantiate?

How can I get prefabs to randomly instantiate? im programming in Java and i just cant get my head around this. Im trying to make a target shooting game where there are a series of different targets to spawn but I’m trying to find a way where there is a rarity in the spawning of some targets. (please help ASAP).

You could spawn all of the targets off screen. You’d just need to figure out what is the max number of targets on screen at any given time. Then you simply teleport your objects into place at the random intervals you want. When they are “shot”, teleport them back off screen again.

I normally program in in c# so there might be some syntax error. I’ll try to put it in java
So first if you have 5 objects you can just do this to get a random number from 0 to 4

var result = Random.Range(0,5);

but if you want some rarer. we need to add weights to the function

function GetWeightedRandom(weights: int[])
{
      var weightTotal = 0;
      for (int i=0;i<weights.Length;i++)
           weightTotal += weights[i];

      var randValue = Random.Range(0,weightTotal);
      var total = 0;
      var result  : int = 0;
      var int (result = 0;result<weights.Length;result++)
      {
                total+=weights[i];
                if (total > randValue)
                    break;
       }
       return result;
}

Now in our code that has our prefabs you need an array of Prefabs and then you need an array of weights. How likely is each on to be done. If you set all the weights to 1 then they will all be equally likely. if you set them all to 1 and one of them to 3… then that on will be 3x more likely than any individual other one. (though if you had 7 items set to 1, and 1 item set to 3… 70% of the time you’d get one of the 1s and 30% of the time you’d get the 3. )

public class PrefabClass : MonoBehaviour
{
        // drag your Prefabs here:
        public Prefabs : GameObject[];
        // and set their weights in the inspector
        public weights : int[]

        function SomeFunction()
        {
                 var whichPrefab = GetWeightedRandom();
                 Instantiate(Prefabs[whichPrefab]);
         }
}

@takatok has the right idea, but something to consider is that you don’t want to keep instantiating gameobjects over and over and over. Instantiate than destroy is much slower than enable/disable. You are better off enabling and disabling objects than constantly spawning new ones if the objects are always the same.

the targets spawn off screen and then move across the screen and destroy forgot to mention that sorry.