Unity C# Problem
In my code, I'm trying to make a sound play once my train hits a certain speed. For example, once it hits 0.06f, play a fast moving sound. However, it just sounds broken. I believe its because its being called to fast.
How could I make it play only once, or just play once it hits 0.06f?
Here is my code:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Movement : MonoBehaviour { public float mSpeed; public float rSpeed; public AudioSource move;
void Start () {
mSpeed = 0f;
rSpeed = .0001f;
}
// Update is called once per frame
void Update () {
transform.Translate (-mSpeed, 0, 0);
// Problem Area !!
if (mSpeed <= 0.06f)
{
move.Play ();
}
// Problem Area !!
if (Input.GetKey ("w"))
{
mSpeed += rSpeed;
}
if (Input.GetKey ("s"))
{
mSpeed += -rSpeed;
}
}
}
Answer by UnityCoach · Mar 23, 2017 at 08:41 PM
You want to use a property for that, it's the best way to trigger things only when a value changes.
private float _mSpeed;
public float mSpeed
{
get { return _mSpeed; }
set
{
if (value != _mSpeed) // if value changed
{
if (_mSpeed <= 0.06f && value > 0.06f) // if previous value is less than and new value is greater than 0.06
{
move.Play ();
}
_mSpeed = value;
}
}
}
void Update ()
{
transform.Translate (-mSpeed, 0, 0);
if (Input.GetKey ("w"))
{
mSpeed += rSpeed;
}
if (Input.GetKey ("s"))
{
mSpeed += -rSpeed;
}
}
Thanks for the reply! Could you explain where or how I should place it. I'm not the best at C#.
Sure, at the root of the $$anonymous$$onoBehaviour. When in Update you change mSpeed, it will call the set method of the accessor, which will trigger the mechanics.
I still can't figure it out. Sorry. Here is my entire script. Could you point out what I am doing wrong?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class $$anonymous$$ovement : $$anonymous$$onoBehaviour { private float _mSpeed; public float mSpeed; public float rSpeed; public AudioSource Horn; public AudioSource move; public AudioSource Bell; public bool BellOn;
{ get {return _mSpeed;} set { if (value !- _mSpeed) { if(_mSpeed <= 0.06f && value > 0.06f)
{
move.Play ();
}
_mSpeed = value;
}
}
}
void Start () {
BellOn = false;
mSpeed = 0f;
rSpeed = .0001f;
}
void Update () {
transform.Translate (-mSpeed, 0, 0);
if (Input.Get$$anonymous$$ey ("w"))
{
mSpeed += rSpeed;
}
if (Input.Get$$anonymous$$ey ("s"))
{
mSpeed += -rSpeed;
}
if (Input.Get$$anonymous$$ey ("h"))
{
Horn.Play ();
}
if (Input.Get$$anonymous$$eyDown ("b"))
{
if (BellOn == true)
{
Bell.Stop ();
BellOn = false;
}
else if (BellOn == false)
{
Bell.Play ();
BellOn = true;
}
}
}
}
Your answer
Follow this Question
Related Questions
Object with rigidbody2D doesn't move when it's supposed to, 0 Answers
Help with pause menu? 0 Answers
How to make a restart button pop up after character has died? 2 Answers
Any tutorials? 1 Answer
Assigning array values to variables 0 Answers