Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

prefab with differents speed

Discussion in '2D' started by ventos, Sep 26, 2016.

  1. ventos

    ventos

    Joined:
    Sep 24, 2016
    Posts:
    4
    Hi, im spawning some object using prefabs, like this

    Code (csharp):
    1.  
    2.   Instantiate(prefab,
    3.   //  transform.position,
    4.   spawnPosition,
    5.   Quaternion.identity);
    6.  
    it works fine, in the prefab,cs script i try to give them each a unique travel pattern, like totally random in all direction

    i tried in start() to

    Code (csharp):
    1.  
    2.   rb = GetComponent<Rigidbody>();
    3.   rb.velocity = new Vector3(Random.Range(-5f, -5f), Random.Range(-5f, -5f), 0);
    4.  
    didn't seem to work, then i moved it to update() and run it only once (using a counter and a IF)

    doesn't work either. at this point, im not sure in which direction i should go.

    Im not sure of the start() and update, are these unique for each new object spawned, or do all the object share same script, i.e. on run of update() internally updates all objects/prefabs

    It seems to me they are unique, but if so, i have even less clue why the code does not work :)

    any pointer would be appreciated

    p.s. im new to programming and game development, only done this in 3-4 days

    Cheers
     
  2. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
    rb.velocity=newVector3(Random.Range(-5f, 5f), Random.Range(-5f, 5f), 0); try from minimum value to maximum value -5 to 5
    different gameobjects can have the same script, but they all will have their own instance (will be unique).
    start or update: with velocity you will change moving vector once in frame. The other forces (like gravity) will try to change this moving vector in the followed frames. If no forces act on the gameobject, then the velocity will stay the same in next frames (your start() method should be added to gameobject, which should be moved, not to spawner).
     
  3. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    I believe vakabaka is correct, your range is between -5 and -5, so it will only output -5.

    Here's a shorthand for getting a random Vector2:
    Code (CSharp):
    1. rb.velocity = Random.insideUnitCircle * 5f;
     
  4. ventos

    ventos

    Joined:
    Sep 24, 2016
    Posts:
    4
    thanks to both of you.. i got it to work using above suggestions :)
     
    LiterallyJeff likes this.