Search Unity

bullet

Discussion in 'Scripting' started by alterus, Sep 26, 2014.

  1. alterus

    alterus

    Joined:
    Sep 9, 2012
    Posts:
    59
    Hello

    I attached to a prefabricated bullet the following piece of code :

    void OnCollisionEnter(Collision collision){

    if(collision.gameObject.tag == "tiger"){
    ContactPoint contact = collision.contacts[0];
    Vector3 pos = contact.point;
    Instantiate(explosionTiger, pos, Quaternion.identity) ;
    Instantiate(smokeTiger, pos, Quaternion.identity ) ;
    gameObject.GetComponent<FSM>().bDead = true; }

    }

    if my prefabricated bullet hits an enemy tank with tag "tiger" the" explosionTiger" and the" smokeTiger" effects are instantiated, no problem but...

    The enemy tank has a "FSM" script attached where I declared a public bool "bDead = false" variable

    I expect that the function ;

    gameObject.GetComponent<FSM>().bDead = true; }

    should switch the bDead variable from false to true, but it does not

    What shall I do ?
     
  2. Pirs01

    Pirs01

    Joined:
    Sep 30, 2012
    Posts:
    389
    First of all: http://forum.unity3d.com/threads/using-code-tags-properly.143875
    Code (csharp):
    1. gameObject.GetComponent<FSM>().bDead = true;
    You're calling GetComponent method of object in gameObject property of this MonoBehaviour class isntance (prefabricated bullet)
    http://docs.unity3d.com/ScriptReference/Component-gameObject.html (MonoBehaviour inherits from Component)

    Code (csharp):
    1. gameObject.GetComponent<FSM>().bDead = true; // is the same as:
    2. this.gameObject.GetComponent<FSM>().bDead = true;
    What you should do instead is call the GetComponent of GameObject you collided with (tank):
    Code (csharp):
    1. collision.gameObject.GetComponent<FSM>().bDead = true;
    http://docs.unity3d.com/ScriptReference/Collision-gameObject.html
     
    Last edited: Sep 27, 2014
  3. alterus

    alterus

    Joined:
    Sep 9, 2012
    Posts:
    59
    yes,it works , thanks