简体   繁体   English

实例化的预制件没有按预期工作,但是当预制件放在现场时,一切都按预期运行

[英]Instantiated prefab is not working as expected but when the prefab is put on the scene then everything runs as expected

I have a script attached to a prefab and the script is:我有一个附加到预制件的脚本,脚本是:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class destroyer : MonoBehaviour
{
    
    Circles circles;

    CircleCollider2D collider1;
    Collider2D collider2;


    private void Start()
    {


        circles = FindObjectOfType<Circles>();

    }
 
    private void OnEnable()
    {
        collider1 = gameObject.transform.GetChild(0).GetComponent<CircleCollider2D>();
        collider2 = gameObject.transform.GetChild(1).GetComponent<Collider2D>();
    }

    private void Update()
    {
        if (transform.position.y < 2)
        {
            Destroy(gameObject);
            circles.instantiator();
            
        }
      



    }
    void OnTriggerStay2D(Collider2D other)
    {
      

        if (collider1.bounds.Contains(other.bounds.max) && collider1.bounds.Contains(other.bounds.min))
       {
            
            if (other.bounds.Contains(collider2.bounds.max) && other.bounds.Contains(collider2.bounds.min))
            {
                
                if (transform.position.y > 3)
                {
                    
                    Destroy(other.gameObject);
                    Destroy(gameObject);
                    circles.instantiator();
                }

            }

        }
    }





}

When I instantiate the prefab the if condition is never running even if the condition is true.当我实例化预制件时,即使条件为真,if 条件也永远不会运行。 But when I put the prefab on the scene and play the game then this if condition is running fine according to the condition.但是当我将预制件放在现场并玩游戏时,如果条件根据条件运行良好。 I am not able to figure out what is the problem in this.我无法弄清楚这是什么问题。

Did you add the children of the prefabs in order.您是否按顺序添加了预制件的孩子。 The GameObject with the 2D circle collider should be first and the 2nd child should have a 2D collider.带有 2D 圆形碰撞器的游戏对象应该是第一个,第二个孩子应该有一个 2D 碰撞器。

Try:尝试:

collider1 = GetComponentInChildren<CircleCollider2D>();
collider2 = GetComponentInChildren<Collider2D>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM