Search Unity

Random instantiation

Discussion in 'Scripting' started by Rutenis, Sep 20, 2014.

  1. Rutenis

    Rutenis

    Joined:
    Aug 7, 2013
    Posts:
    297
    Hey, so i want to instantiate a random object in to the scene, so im using arrays. But it doesnt seem to work, it only instantiate the first object in the array. Whats the problem?

    -Thanks! :))

    Script:

    Code (csharp):
    1. public Transform[] BloodSplatter;
    2.  
    3. Instantiate(BloodSplatter[Random.Range(0, 1)], new Vector3(Random.Range(0.04f, 0.97f), Random.Range(0.94f, 0.07f), 0), transform.rotation);
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Random.Range (0, 1) will only ever return 0, since the max value is exclusive. Anyway you should not hard-code values, but use the array length. i.e., bloodSplatter.Length.

    --Eric
     
    Rutenis likes this.
  3. Rutenis

    Rutenis

    Joined:
    Aug 7, 2013
    Posts:
    297
    Oh okay, that makes a lot of sense. Thanks. :))
     
  4. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    As Eric5h5 said, this way it'll work for any size array.
    Code (csharp):
    1. public Transform[] BloodSplatter;
    2.  
    3. Instantiate(BloodSplatter[Random.Range(0, BloodSplatter.Length)], new Vector3(Random.Range(0.04f, 0.97f), Random.Range(0.94f, 0.07f), 0), transform.rotation);
     
    BmxGrilled likes this.
  5. Rutenis

    Rutenis

    Joined:
    Aug 7, 2013
    Posts:
    297
    Yeah, eric explaned the problem, thanks again tho. :)