Search Unity

How can I pass a variable to OnCollisionEnter2D?

Discussion in 'Scripting' started by videoanime, Feb 1, 2015.

  1. videoanime

    videoanime

    Joined:
    Sep 28, 2014
    Posts:
    42
    Hi everyone, can somebody help me? I created a private variable, that I feed from other script, but when I want to use it in OnCollisionEnter2D it's equal to zero, not to my new value, here's the code:

    Code (CSharp):
    1. private int sd;
    2.  
    3.     void Start()
    4.         {
    5.         Debug.Log (sd + " start");
    6.         }
    7.  
    8.     // Update is called once per frame
    9.     void Update ()
    10.         {
    11.         Debug.Log (sd + " update");
    12.         }
    13.  
    14.     public void indice(int ID)
    15.         {
    16.         sd = ID;
    17.         Debug.Log (sd + " indice");
    18.         }
    19.  
    20.     void OnCollisionEnter2D(Collision2D coll)
    21.         {
    22.         if (coll.gameObject.tag == "Finish" && sd != 0)
    23.             {
    24.             Debug.Log (sd + " colision");
    25.             }
    26.         }
    As you can see, the only part that the value is correct is here Debug.Log (sd + " indice");, in the other parts always is printed as a zero. Can somebody tell me what am I doing wrong?
     
  2. Ruekaka

    Ruekaka

    Joined:
    Sep 12, 2014
    Posts:
    119
    Check all places where you call indice(). I guess there must be a place where you set to 0 again.
    Or (I guess the code is just an excerpt of your script) there's a piece of code where you set sd to 0 again.
     
  3. videoanime

    videoanime

    Joined:
    Sep 28, 2014
    Posts:
    42
    I call indice() in other script that is my "spawner", because I can spawn randomly pieces from that, so, when I spawn them, since there I spawn an id, I send that id to this script, as you can see I asign a value to "sd", I can print well with Debug.Log (sd + " indice"); but printing in other parts of the script results as zero e.g.

    Debug.Log (sd + " start"); prints "0 start"
    Debug.Log (sd + " update"); prints "0 update" and
    Debug.Log (sd + " colision"); printos "0 colision"

    It's like even the "sd" variable is usable in all the script, it couldn't get out of the function indice() and I don't understand why.