Search Unity

Instantiating at random local position.

Discussion in 'Scripting' started by Rutenis, Oct 31, 2014.

  1. Rutenis

    Rutenis

    Joined:
    Aug 7, 2013
    Posts:
    297
    Hey, so i have been trying to instantiate an object at random local position but it doesnt seem to work. I've tried setting the instantiated object to be a child of that object, wich has the local position that i need, Any ideas?

    -Thanks! :)

    Simple code:
    Code (csharp):
    1.  
    2. Transform DamageTextPrefab = Instantiate(DamageText10, new Vector3(Random.Range(-0.0897828f, 0.07099215f), 0.108575f, -0.2966309f), transform.rotation) as Transform;
    3.             DamageTextPrefab.transform.parent = transform;
    4.  
    5.  
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,539
    You're typing your object as a Transform when calling Instantiate. Is your prefab a transform? I'm betting it's a GameObject, not a Transform.
     
  3. Rutenis

    Rutenis

    Joined:
    Aug 7, 2013
    Posts:
    297
    It is a Transform. Never mind, ended up fixing it myself, actually it was easy. Thanks for the help anyway. :))

    How i fixed it:

    Code (csharp):
    1.  
    2. var randPosition = new Vector3(Random.Range(xMin, xMax), yDmgPos, -2);
    3. Transform DamageTextPrefab5 = Instantiate(DamageText5, transform.localPosition + randPosition, Quaternion.identity) as Transform;
     
    Last edited: Oct 31, 2014