RequireCollider

  06. Attributes No Comments

When added before a component class will make sure that whenever the component with the attribute is added to GameObjects, a collider will also be present on the same GameObject.

Attribute Target

Component class

Example

using UnityEngine;
using Sisus.Attributes;
using JetBrains.Annotations;

[RequireCollider, RequireComponent(typeof(Rigidbody)), DisallowMultipleComponent]
public class CollisionSoundEmitter : MonoBehaviour
{
	[NotNull]
	public AudioClip audioClip;
	[Range(0f, 1f)]
	public float minVolume = 0.1f;
	[Range(0f, 1f)]
	public float maxVolume = 1f;
	[Min(0.00001f)]
	public float velocityRelativeVolumeMultiplier = 0.25f;

	void OnCollisionEnter(Collision collision)
	{
		foreach(var contact in collision.contacts)
		{
			float volume = collision.relativeVelocity.magnitude * velocityRelativeVolumeMultiplier;
			if(volume > minVolume)
			{
				if(volume > maxVolume)
				{
					volume = maxVolume;
				}
				AudioSource.PlayClipAtPoint(audioClip, contact.point, volume);
			}			
		}
	}
}

Example Result

 

See also: RequireCollider2D