- Home /
Animation play only when in range
I am new to both unity and java script, so I'm having some trouble. I have an object with an animation (Take 001). I want this animation to play and loop only when it's within a certain range of the object tagged 'player'. When it's out of range I want the animation to stop. I found a few similar questions to this on here, but didn't give me quite what I was looking for.
Answer by Ingen · Jul 12, 2012 at 06:06 AM
hallo
add this script at the object, if don't rotate only remove part relative the rotation
in hierarchy set range and add the animation
This script doesn't let you place a script. It only lets you select prefabs
excuse me, what you speak about?
I usually use this to catch the player, rotate some turret, animate the gun, and work good
maybe you have not try it, or set something wrong
please explain what intend with"This script doesn't let you place a script."?
what you wont to do?
glad to help if I can :)
Wait, does this script go on the object that is being animated?
facepalm The reason it wasn't working was because I left play automatically on -_-
no the script go in rotating part then drag the animated object to "animatedObj1" var
you can easily add function for shoot, and call them in the latest if
E$$anonymous$$PTY GameObject
\/
Base
Rotating part - contain the script
\/
animated object
Answer by Tommynator · Jul 31, 2012 at 03:44 AM
Something like this?
using UnityEngine;
class PlayAnimation : MonoBehaviour
{
public float range = 5;
private Transform player;
void Start()
{
player = GameObject.FindWithTag("Player").GetComponent<Transform>();
}
void Update()
{
if (Vector3.Distance(player.position, transform.position) < range)
{
if (!animation.isPlaying) animation.Play();
}
else
{
if (animation.isPlaying) animation.Stop();
}
}
}