Unity3D – Create a Class – Easy Example

Watch the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#pragma strict
 
class Audio // create a Class, you will have the tringle to expand Class content into Inspector
{
    var crunchSFX : AudioClip; // Assign in Inspector
}
var myAudioClass : Audio; // store the whole Class content inside a variable
 
  
function OnTriggerEnter(other : Collider)
{
    // play the SFX calling Class
    audio.PlayOneShot(myAudioClass.crunchSFX, 1);
     
} // END OnTriggerEnter

The steps are:
1. Create a Class

1
2
3
4
class Audio
{
    var crunchSFX : AudioClip; // Assign in Inspector
}

2. Store the whole Class content inside a variable

1
var myAudioClass : Audio;

3. Call the Class content using the statement:

1
2
//  variable with Class content . variable name
... myAudioClass.crunchSFX ...