Search Unity

Getting id of object

Discussion in 'Getting Started' started by witcher101, Sep 24, 2015.

  1. witcher101

    witcher101

    Joined:
    Sep 9, 2015
    Posts:
    516
    public GameObject hazard;
    Rigidbody gm=Instantiate (hazard, spawnPosition, spawnRotation) as Rigidbody;
    gm.AddForce(0f,50,0f);

    I am trying to get id of created object and add force to it.
    Above code is giving object reference not set to instance of object error.

    How do i do this
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    With "as" you are trying to typecast your GameObject to a Rigidbody. But it's not a Rigidbody (even if it has a Rigidbody component). So the typecast will return null. I think you mean to do:

    Code (CSharp):
    1. GameObject noob = Instantiate(hazard, spawnPosition, spownRotation) as GameObject;
    2. Rigidbody gm = noob.GetComponent<Rigidbody>();
    3. gm.AddForce(0, 50, 0);
    (Though adding a force for a single frame like this won't have a very good effect — you generally need to add force over several frames. For a newly spawned object, you're often better off simply setting the rigidbody velocity instead.)
     
    jhocking likes this.