5
\$\begingroup\$

I am writing some code in JavaScript for a ray cast shooting program. I have all the variables I need except for sound, and I'm not too sure on how to add that variable into my code. I would really appreciate any help people can give to solve this problem, and show me how to add a sound variable to my code.

#pragma strict

var Effect : Transform;
var Damage = 100;

function Update () {

	var hit : RaycastHit;
	var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*0.5, Screen.height*0.5, 0)); 
	
	if (Input.GetMouseButtonDown(0))
	{
		if (Physics.Raycast (ray, hit, 100))
		{
			hit.transform.SendMessage("ApplyDamage", Damage, SendMessageOptions.DontRequireReceiver);
		}
	}
}

\$\endgroup\$
  • 1
    \$\begingroup\$ Look here. \$\endgroup\$ – Exerion Oct 24 '15 at 8:47
  • \$\begingroup\$ I also recommend switching to C# as soon as possible. It takes all of three regex replacements: var foo : Bar; -> Bar foo;, function foo() : Bar -> public Bar foo(), and (for parameters inside functions) foo : Bar -> Bar foo (which you can catch with the first, if the first just removes the var) \$\endgroup\$ – Draco18s Mar 16 '18 at 17:05
1
\$\begingroup\$

You'll need to add an audio source to your GameObject and assign it with an AudioClip, then you can play the sound like this when your raycast hits something.

#pragma strict

var Effect : Transform;
var Damage = 100;
var AudioSource : AudioSource;

function Start () {
    AudioSource = GetComponent.<AudioSource>();
}

function Update () {
    var hit : RaycastHit;
    var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*0.5, Screen.height*0.5, 0)); 

    if (Input.GetMouseButtonDown(0))
    {
        if (Physics.Raycast (ray, hit, 100))
        {
            hit.transform.SendMessage("ApplyDamage", Damage, SendMessageOptions.DontRequireReceiver);
            AudioSource.Play();
        }
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.