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. Dismiss Notice

Need help translating js to c#

Discussion in 'Scripting' started by Steikepanne, Dec 15, 2017.

  1. Steikepanne

    Steikepanne

    Joined:
    Jan 30, 2017
    Posts:
    34
    Need some help translating this js script to c#

    It works just fine, but I would like it in c# as im most familiar with that and I have no clue how to translate it :/
    You can destroy enemies by clicking them, and different enemies require a different amount of clicks.


    Code (JavaScript):
    1. #pragma strict
    2.  
    3. var amountOfClicks:int=0;
    4.  
    5. function OnMouseDown(){
    6.    if(amountOfClicks>1)
    7.    {
    8.         Destroy(gameObject);
    9.    }
    10.    else{
    11.      amountOfClicks++;
    12.    }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,711
    In that case, make a C# Monobehavior class file named whatever you call this JS file.

    Create an amountOfClicks as a public int

    Declare the OnMouseDown() method (it's special, so see Unity docs for the precise signature and capitalization).

    Copy/paste your logic inside.

    This is an excellent example for you to learn how easy it can be.
     
  3. Antony-Blackett

    Antony-Blackett

    Joined:
    Feb 15, 2011
    Posts:
    1,772
    Code (csharp):
    1.  
    2. int amountOfClicks = 0;
    3.  
    4. void OnMouseDown()
    5. {
    6.   if( amountOfClicks > 1 )
    7.   {
    8.     Destroy(gameObject);
    9.   }
    10.   else
    11.   {
    12.     amountOfClicks++;
    13.   }
    14. }
     
  4. Steikepanne

    Steikepanne

    Joined:
    Jan 30, 2017
    Posts:
    34
    Kurt: Thanks, I'm somewhat new to coding and was a bit confused. But you pointed me in the right direction :)
    And I tried translating it myself earlier but it didnt work (Dont know why), but now it works :D
     
  5. marcV2g

    marcV2g

    Joined:
    Jan 11, 2016
    Posts:
    115
    For unity non ui input handling

    Code (CSharp):
    1.  
    2. //method called every frame
    3. void Update()
    4. {
    5. //if mouse button down
    6. if (Input.GetMouseButtonDown(0))
    7. {
    8. //do stuff here
    9. }
    10.  
    11. }
     
  6. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    12,528