RayCast and Animation not working
I am using the FPS Controller as the Player and tagged as Player. I am using a Soldier I downloaded from the Asset Store titled “Friendly Soldier” as the enemy.
Currently the Enemy is not tagged. On the Soldier I attached a script titled “Look Player” which works fine as he will turn and look at the FPS Controller in any direction the FPS Controller attempts to walk around him. This is the following script that works.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class LookPlayer : MonoBehaviour { public Transform thePlayer;
void Update()
{
transform.LookAt(thePlayer);
}
}
On the Enemy or Soldier, there is an empty GameObject that was renamed as EnemyAI. There are two animations connected to the Soldier or Enemy which are Idle and FirePistol. The script that is attached to the EnemyAI is named SoldierAI. There is a second empty GameObject attached to the soldier named FireSound. The script requires dragging the soldier itself from the Heirarchy tab to the Inspector Tab to the field titled The Soldier. Same with FireSound be dragged to Fire Sound. The empty GameObject is in the center and in front of the Soldier in Scene view. The SoldierAI script is attached to the EnemyAI GameObject and the code is the following:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class SoldierAI : MonoBehaviour { public string hitTag; public bool lookingAtPlayer = false; public GameObject theSoldier; public AudioSource fireSound; public bool isFiring = false;
public float fireRate = 1.5f;
void Update ()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit))
{
hitTag = hit.transform.tag;
}
if (hitTag == "Player" && isFiring == false)
{
StartCoroutine(EnemyFire());
}
if (hitTag != "Player")
{
theSoldier.GetComponent<Animator>().Play("Idle");
lookingAtPlayer = false;
}
}
IEnumerator EnemyFire()
{
isFiring = true;
theSoldier.GetComponent<Animator>().Play("FirePistol");
fireSound.Play();
lookingAtPlayer = true;
yield return new WaitForSeconds(fireRate);
isFiring = false;
}
}
In Game Mode the Soldier remains in the Idle state, continuously looking at the FPS Controller regardless of what position the Controller may be but the Animation for FirePistol is NOT taking place. Can someone advice a fix for this???
Your answer
Follow this Question
Related Questions
NEED HELP ANIMATING PLAYER MOVEMENT 0 Answers
Animator script 0 Answers
Raycasting Animations 0 Answers
Using same animator for multiple game objects 0 Answers
How to call Animator from another script 0 Answers