Greetings everyone! I have been playing with collisions and sound playing after Lecture 53 of Unity 3D and I am trying to figure out the most “acceptable” or the best practice to play a sound after a collision. In my case, (Getting the PowerUp) I do the following in code:
public class PowerUp : MonoBehaviour
{
AudioSource audioSource;
MeshRenderer meshRenderer;
SphereCollider sphereCollider;
void Start()
{
audioSource = GetComponent<AudioSource>();
meshRenderer = GetComponent<MeshRenderer>();
sphereCollider = GetComponent<SphereCollider>();
}
void Update()
{
}
void OnCollisionEnter(Collision collision)
{
switch (collision.gameObject.tag)
{
case "Player":
print("Powered up!");
meshRenderer.enabled = false;
sphereCollider.enabled = false;
audioSource.Play();
break;
default:
break;
}
}
}
I am disabling both the Mesh Rendered and the Collider, the reason being that if I want to disable the object, then the sound won’t play. Also, no other method can be used in Update after disabling the object, so I can’t use gameObject.activeSelf afterwards.
I did also try to play the sound, then used a while loop to wait until it finishes, then disabled the object, but that crashed Unity as a whole.
This might seem like a very simple question to answer, but I am really confused here, so I just disabled those two things I mentioned above. Any other better option to play a sound?