Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question In unity, how do i get random selects prefabs and random height between 8 to 10

Discussion in 'Scripting' started by TaraDinReinwald23, Feb 11, 2023.

  1. TaraDinReinwald23

    TaraDinReinwald23

    Joined:
    Feb 11, 2023
    Posts:
    3
    hi i need help with is projects in c# how do get a randomly selected prefabs from a serialized array of prefabs and I have 3 different prefabs, that random selected height between 8 and 10.

    Thank you
     
  2. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    4,397
    myArray[Random.Range(0, myArray.length)]

    That selects a random item. What do you mean with the height stuff?
     
    TaraDinReinwald23 likes this.
  3. QuinnWinters

    QuinnWinters

    Joined:
    Dec 31, 2013
    Posts:
    490
    For random height of the prefabs I assume you mean the transform.y scale. What I posted below assumes you want an x and z scale of 1 on the objects.
    Code (CSharp):
    1. float newYScale = Random.Range (8, 10);
    2. instantiatedObject.localScale = new Vector3 (1, newYScale, 1);
    If it's position you're speaking of you would do the same thing but for instantiatedObject.position.
     
    TaraDinReinwald23 likes this.
  4. TaraDinReinwald23

    TaraDinReinwald23

    Joined:
    Feb 11, 2023
    Posts:
    3
    sorry about that i mean that when I'm building a tower that has random selected height between 8 and 10.
     
  5. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    4,397
    Either make a linq statement or use a list. Iterate over the array, add every tower in that range, then pick a tower from that list
     
  6. TaraDinReinwald23

    TaraDinReinwald23

    Joined:
    Feb 11, 2023
    Posts:
    3
  7. BenevolenceGames

    BenevolenceGames

    Joined:
    Feb 17, 2021
    Posts:
    128
    Array.Find(i => i.height >= minHeight && i.height <= maxHeight)
    I think that should do it
     
    TaraDinReinwald23 likes this.