Unity Tips

Confused about Unity Scripting?


using UnityEngine;
using System.Collections;

public class Hitsound : MonoBehaviour {
    void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.gameObject.tag == areas)

        GetComponent<AudioSource>().Play();
         
    }

}


Take a look at the script above and you will see these lines:

    void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.gameObject.tag == areas)

What i have always found confusing as a beginner is that as well as the word Collision there are also other words called collision (Red) without the capital at the beginning. Most tutorials online often use the same words for different functions so it is useful to know that the second word collision can be changed to whatever you like, with some exceptions. The script still works if you change the word “collision” to the word “hit”. So, to make things much less confusing i have decided in my tutorials to not double up naming in this way, so they don’t look so confusing to a beginner.

Something else to remember is that where you see the line:
public class Hitsound : MonoBehaviour
The word Hitsound is the name of your script, so this word should match your scripts name.I have often had scripts not work because of these names not matching.

A good place to start learning about Unity Scripting is:
unity3d.com/learn/tutorials/topics/scripting