我有一个附加到空GameObject名称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;
}
}
在Npc的射击脚本中,正在获取Sci-Fi_Soldier-Prefab的Sci-Fi_Soldier对象子代。 Sci-Fi_Soldier具有Animator组件。
这与第一个Sci-Fi_Soldier-Prefab配合良好。
但是第二个重复的Sci-Fi_Soldier-Prefab(1)只是不停地行走,而不像第一个那样。我希望该脚本能够控制并在所有Sci-Fi_Soldier-Prefabs上运行。
答案 0 :(得分:1)
您的射击脚本定义了一个
Public GameObject npc;
这是正在运行的npc。它没有引用其他重复的NPC,因此不会对其造成影响。如果您将npc更改为
之类的GameObjects列表List<GameObject> npcList;
,然后将所有NPC添加到其中,然后更改操作以对列表的每个成员进行操作,它将影响所有NPC。