How to trigger animation from object colliding with another?
In my project I have the it when you drop Object 1 onto Object 2 it should play the sound of a door opening, as well as play the animation of the door opening. Right now only the sound is playing but not the animation. I have a separate script that plays the door animation by pressing a button which works.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class CollideDoorOpen : MonoBehaviour {
public Animator anim; //this is the animation holder where you place the animatior
public AudioClip SoundToPlay; // audio for the door when it opens
public AudioSource SoundSource; // the object where the audio comes from
public bool alreadyPlayed = false; // makes the animation unplayed so it can go off once
// Start is called before the first frame update
void Start()
{
SoundSource.clip = SoundToPlay; //grabs the audio source that the user puts in and plays from soundsource when triggered
anim = GetComponent<Animator>(); // grabs the animator
}
void OnCollisionEnter(Collision col)
{
if (!alreadyPlayed)
{
if (col.gameObject.name == "RedPlatform")
{
anim.Play("Door_Open"); //runs the door animation
SoundSource.Play();// plays the audio clip
alreadyPlayed = true; // once the audio plays the script will turn on already played so it won't play again
}
}
}
}
Comment