Search Unity

Converting MeleeSystem by Brackeys to C# (most likely a silly mistake)

Discussion in 'Scripting' started by tom288, Dec 18, 2014.

  1. tom288

    tom288

    Joined:
    Dec 20, 2012
    Posts:
    4
    I haven't gotten used to c# syntax or error messages, so this is probably pretty simple to solve. I am trying to replicate the following code in C#:
    http://s9.postimg.org/pwco3xt7z/Melee_System_Brackeys.png
    (if this link breaks, the video is
    )

    This is my failed attempt:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class MeleeSystem : MonoBehaviour {
    5.  
    6.     public int theDamage = 50;
    7.     public float distance;
    8.  
    9.     void Update()
    10.     {
    11.         if (Input.GetButtonDown("Fire1"))
    12.         {
    13.             RaycastHit hit;
    14.             if (Physics.Raycast (transform.position, transform.TransformDirection(Vector3.forward), hit))
    15.             {
    16.                 distance = hit.distance;
    17.                 hit.transform.SendMessage("Hurt", theDamage, SendMessageOptions.DontRequireReceiver);
    18.             }
    19.         }
    20.     }
    21. }
    22.  
    These are my errors:
    Code (CSharp):
    1. Assets/MeleeSystem.cs(14,113): error CS0165: Use of unassigned local variable `hit'
    2. Assets/MeleeSystem.cs(14,37): error CS1502: The best overloaded method match for `UnityEngine.Physics.Raycast(UnityEngine.Vector3, UnityEngine.Vector3, out UnityEngine.RaycastHit)' has some invalid arguments
    3. Assets/MeleeSystem.cs(14,37): error CS1620: Argument `#3' is missing `out' modifier
    If someone familiar with C# could spend a minute comparing the two programs, I would appreciate it :)
     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    Notice the added 'out'
    Code (csharp):
    1. if(Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit))
     
    tom288 likes this.
  3. Fluzing

    Fluzing

    Joined:
    Apr 5, 2013
    Posts:
    815
    Put "out" in front of hit in the raycast.
     
    tom288 likes this.
  4. tom288

    tom288

    Joined:
    Dec 20, 2012
    Posts:
    4
    Thank you! I looked at it for ages, I can't believe I didn't spot that. :D
    Sorry for the late reply, I didn't realize that created threads were not watched automatically on the unity forums.