Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Resolved Change a Int on collision or trigger

Discussion in 'Editor & General Support' started by whycantipickaname, May 28, 2020.

  1. whycantipickaname

    whycantipickaname

    Joined:
    Feb 21, 2020
    Posts:
    14
    so im somewhat new to unity and i was wondering if i could do
    Code (CSharp):
    1. OnCollisionEnter(Collision Col)
    2. {
    3. // this is the part i need help with
    4. if(player.tag=Player)
    5. {
    6. Change int gunDamage +1
    7. Destroy GameObject gunDamageUp
    8. }
    the name of the value i want to change is gunDamage
     
  2. DiegoDePalacio

    DiegoDePalacio

    Unity Technologies

    Joined:
    Oct 28, 2009
    Posts:
    506
    Hi @lucascleg,

    You can definitely do that. Your code will look like this:

    Code (CSharp):
    1. void OnCollisionEnter(Collision collision)
    2. {
    3.     if (collision.gameObject.CompareTag("Player"))
    4.     {
    5.         gunDamage++;
    6.         Destroy(gunDamageUp);
    7.     }
    8. }
    You can find more information about `CompareTag` here: https://docs.unity3d.com/ScriptReference/Component.CompareTag.html


    Happy learning!


    P.D. I have some recommendations on how you're coding:
    1. You should make sure that `gunDamage` and `gunDamageUp` variables are of type `int` and `GameObject` respectively and are declared on the same class in where the `OnCollision` method is being used.
    2. Also, you need to make sure that the variable names that you're using are descriptive enough of what you're doing.
    3. Finally, you can consider adding some comments to your code, because right now, it is impossible to know what you're trying to accomplish inside of your `if` block.
     
    Last edited: May 28, 2020
    whycantipickaname likes this.
  3. whycantipickaname

    whycantipickaname

    Joined:
    Feb 21, 2020
    Posts:
    14
    wow thats a lot of info thanks very much for the help
     
    DiegoDePalacio likes this.