Search Unity

Getting the same random value for all generated prefabs

Discussion in 'Scripting' started by SnailGirl, Aug 10, 2017.

  1. SnailGirl

    SnailGirl

    Joined:
    May 18, 2017
    Posts:
    11
    Hello everyone!

    I'm currently setting up a scene to randomly create characters. And it works fine, textures and blend shapes generate randomly. However, for the ear prefab, I'd like to make the ears reference the same mesh. Random ears might be a bit much. Also, sometimes the ears don't pick up a mesh at all and I get only one ear (I've double checked the file names, that doesn't seem to be it).

    I'd like to keep the random size of the ears, but make sure that the gameobjects always reference the same random mesh.

    Here's a picture to demonstrate my issue:


    Here's the script I use:
    Code (CSharp):
    1.  
    2. public class randomizer : MonoBehaviour {
    3.  
    4.     public string File_name;
    5.     public int count;
    6.     public bool sizeRandom;
    7.     public float size;
    8.  
    9.  
    10.     private void Start()
    11.     {
    12.         int id = Random.Range(0, count) + 1;
    13.         MeshFilter filter = gameObject.GetComponent<MeshFilter>();
    14.         CapsuleCollider collider = gameObject.GetComponent<CapsuleCollider>();
    15.  
    16.         filter.mesh = Resources.Load<Mesh>(File_name +"0"+ id) as Mesh;
    17.         Bounds msh_bounds = filter.mesh.bounds;
    18.         collider.radius = (msh_bounds.size.x + msh_bounds.size.z) * 0.25f;
    19.         collider.height = msh_bounds.size.y;
    20.  
    21.      
    22.         if (sizeRandom == true)
    23.         {
    24.             float newsize = Random.Range((size - size * 0.5f), (size + size * 0.5f));
    25.             gameObject.transform.localScale = new Vector3 (newsize, newsize, newsize);
    26.  
    27.         }
    28.  
    29.     }
    30.  
    31. }
    32.  

    This is only my second project using C#, but I'm sure there must be a way of using an if statement or something similar in this case? I'd appreciate any ideas! :)

    thanks in advance
     
    Last edited: Aug 10, 2017
  2. SnailGirl

    SnailGirl

    Joined:
    May 18, 2017
    Posts:
    11
    Well, this feels stupid, answering myself only minutes later. But in case someone else needs a similar solution:

    I simply moved the part where the "id" is being set to be in a void Awake instead of in the void Start, like this:

    Code (CSharp):
    1.  private void Awake()
    2.     {
    3.         id = Random.Range(0, count) + 1;
    4.     }
     
  3. gbr247336

    gbr247336

    Joined:
    Sep 30, 2020
    Posts:
    1
    God!! that's so random :D:D