I have a script that attached to empty GameObject name Shooting :
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooting : MonoBehaviour
{
[Header("Main")]
public GameObject npc;
public Transform[] firePoints;
public Rigidbody bulletPrefab;
public float launchForce = 700f;
public bool automaticFire = false;
public float bulletDestructionTime;
[Space(5)]
[Header("Slow Down")]
public float maxDrag;
public float bulletSpeed;
private bool bulletsSlowDown = false;
public bool overAllSlowdown = false;
[Range(0, 1f)]
public float slowdownAll = 1f;
private Animator anim;
private void Start()
{
anim = npc.GetComponent<Animator>();
anim.SetBool("Shooting", true);
}
public void Update()
{
if (overAllSlowdown == true)
{
Time.timeScale = slowdownAll;
}
if (isAnimationStatePlaying(anim, 0, "AIMING") == true)
{
if (Input.GetButtonDown("Fire1") && automaticFire == false)
{
if (anim.GetBool("Shooting") == true)
{
anim.Play("SHOOTING");
LaunchProjectile();
}
}
else if (Input.GetButtonDown("Fire1") && automaticFire == true)
{
automaticFire = false;
}
else
{
if (Input.GetButtonDown("Fire2"))
{
automaticFire = true;
}
if (automaticFire == true)
{
anim.Play("SHOOTING");
LaunchProjectile();
}
}
}
}
private void LaunchProjectile()
{
foreach (var firePoint in firePoints)
{
Rigidbody projectileInstance = Instantiate(
bulletPrefab,
firePoint.position,
firePoint.rotation);
projectileInstance.AddForce(new Vector3(0, 0, 1) * launchForce);
if (bulletsSlowDown == true)
{
if (projectileInstance != null)
{
StartCoroutine(AddDrag(maxDrag, bulletSpeed, projectileInstance));
}
}
if ((automaticFire == true || automaticFire == false) && bulletsSlowDown == false)
{
projectileInstance.gameObject.AddComponent<BulletDestruction>().destructionTime = bulletDestructionTime;
projectileInstance.gameObject.GetComponent<BulletDestruction>().Init();
}
}
}
IEnumerator AddDrag(float maxDrag, float bulletSpeed, Rigidbody rb)
{
if (rb != null)
{
float current_drag = 0;
while (current_drag < maxDrag)
{
current_drag += Time.deltaTime * bulletSpeed;
rb.drag = current_drag;
yield return null;
}
rb.velocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
rb.drag = 0;
rb.gameObject.AddComponent<BulletDestruction>().destructionTime = bulletDestructionTime;
rb.gameObject.GetComponent<BulletDestruction>().Init();
}
}
bool isAnimationStatePlaying(Animator anim, int animLayer, string stateName)
{
if (anim.GetCurrentAnimatorStateInfo(animLayer).IsName(stateName))
return true;
else
return false;
}
}
In the shooting script at the Npc it's getting the Sci-Fi_Soldier object child of the Sci-Fi_Soldier-Prefab. The Sci-Fi_Soldier have the Animator component.
And this is working fine with the first Sci-Fi_Soldier-Prefab.
But the second duplicated Sci-Fi_Soldier-Prefab (1) is just keep walking non stop and not like the first one. I wanted that the script will control and work on all the Sci-Fi_Soldier-Prefabs.