【问题标题】:Instances of prefab aren't being controlled separately预制件的实例没有被单独控制
【发布时间】:2020-03-02 04:48:55
【问题描述】:

我在一个关卡中设置了多个敌人,所有敌人都使用相同的行为和动画脚本。当我击中或杀死其中一个时,他们都会被击中或杀死。我需要它们作为单独的实例运行。

我已尝试仅引用脚本的一个实例:

 private GoblinBehaviour goblin;
  goblin = GetComponent<GoblinBehaviour>();
        goblin.IncrementHits(1);

但这不起作用。出现一个错误,说明无法使用实例访问脚本,而是需要一个类型。

命中检测脚本代码:

   public class RangedDetection : MonoBehaviour
   {
   private GoblinBehaviour goblin;
   void OnTriggerEnter(Collider other)
    {
    //on colliding destroy rocks after its life time
    Destroy(gameObject, rockLifeTime);

    if (other.gameObject.tag.Equals("Enemy"))
    //if (other.tag == "Enemy")
    {
        Destroy(other.gameObject);
    }
    else if (other.gameObject.tag.Equals("Goblin"))//goblin should play 
 death animation
    {
       goblin = GetComponent<GoblinBehaviour>();
        goblin.IncrementHits(1);
        GetComponent<BoxCollider>().enabled = false; //Removing hit 
 collider so it only hits target once.
    }
 }
 }

地精脚本的简化代码:

 public class GoblinBehaviour : MonoBehaviour
 {
Transform player;

public static bool isDead;
public static bool isPunching;
public static bool isHit;
public GameObject particles;
public Animator anim;


 public void IncrementHits(int hitCount)
 {
    isHit = true;
    hits += hitCount;
    if (hits >= 2) isDead = true;


}

void Die()
{
    Instantiate(particles, transform.position, transform.rotation);
    Destroy(gameObject);

}


void updateAnim()
{
    anim.SetBool("Punch_b", isPunching);
    anim.SetBool("hit", isHit);

}

}

事物应该分别设置动画和动作,我不确定如何仅引用脚本的当前实例。

【问题讨论】:

  • 请提供您的 GoblinBehaviour 脚本。看起来您使用的是静态方法而不是实例方法。
  • @Erik 已编辑,谢谢
  • @Lady 您的“简化”GoblinBehaviour 脚本不会产生有问题的错误:(“出现一个错误,表明无法使用实例访问脚本,而是需要一个类型” )。寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定问题或错误以及在问题本身中重现它所需的最短代码。没有明确的问题陈述对其他读者没有用处。见:How to create a Minimal, Reproducible Example.
  • 您的“命中”属性也是静态的吗? @女士

标签: c# unity3d instance animator


【解决方案1】:

虽然您的代码不完整且问题无法确定,但您似乎使用不正确的静态方法。

静态属性与实例类似。换句话说,所有地精实例共享任何静态属性(isPunching、isHit、isDead 等)。将这些值设为静态允许您直接引用它们而无需获取您正在影响的实例,但会导致您一次更新所有地精。

您的解决方案将涉及从您的 GoblinBehaviour 属性中删除静态修饰符,除非这些属性旨在在所有实例之间共享。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    相关资源
    最近更新 更多