Ive been trying to get this right for ages and ive decided to ask you guys.
Does anyone have any idea why its not playing the animation when i assign this script to the parent of the model im trying to animate?
using UnityEngine;
using System.Collections;
public class EnemyAnimation : MonoBehaviour
{
Animation _animation;
void Start()
{
_animation = GetComponentInChildren();
string animationToPlay = "";
switch (Random.Range(0,3))
{
default:
case 0:
animationToPlay = "Move1";
break;
case 1:
animationToPlay = "Move2";
break;
case 2:
animationToPlay = "Move3";
break;
}
_animation[animationToPlay].wrapMode = WrapMode.Loop;
_animation.Play(animationToPlay);
_animation[animationToPlay].normalizedTime = Random.value;
}
}
Unity debug screen was saying the line “_animation[animationToPlay].wrapMode = WrapMode.Loop;” was wrong.
Sorry if i haven’t displayed this correctly Just any help would be much appreciated!
This line is causing the error:
_animation[animationToPlay].wrapMode = WrapMode.Loop;
because you are using a string to access an element of an array, which should be accessed using an integer of somesort.
So in your Start() function add these bits:
// at the top with _animation
int animToPlay;
// then in each case of your switch do this
case 0:
animationToPlay = "Move";
animToPlay = 0; // 1, 2, 3 etc depending on the case
break;
// then at the bottom change the code to:
_animation[animToPlay].wrapMode = WrapMode.Loop
_animation.Play(animationToPlay);
_animation[animToPlay].normalizedTime = Random.value;
Hope this helps.
using UnityEngine;
using System.Collections;
public class EnemyBodyScript : MonoBehaviour {
void Start() {
int
_animation = GetComponentInChildren();
string animationToPlay = "";
switch (Random.Range (0, 3)) {
default:
case 0:
animationToPlay = "Move1";
animationToPlay = 0;
break;
case 1:
animationToPlay = "Move2";
animationToPlay = 1;
break;
case 2:
animationToPlay = "Move3";
animationToPlay = 2;
break;
case 3:
animationToPlay = "Move4";
animationToPlay = 3;
break;
case 4:
animationToPlay = "Move5";
animationToPlay = 4;
break;
case 5:
animationToPlay = "Move6";
animationToPlay = 5;
break;
case 6:
animationToPlay = "Move7";
animationToPlay = 6;
break;
}
_animation[animationToPlay].wrapMode = WrapMode.Loop;
_animation.Play(animationToPlay);
_animation[animationToPlay].normalizedTime = Random.value;
}
}