在运行时添加/删除组件 [英] Add/Remove Components in runtime

查看:264
本文介绍了在运行时添加/删除组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在脚本(c#)中创建一个多维数据集.我要删除BoxCollider,因为我正在开发2D游戏并通过BoxCollider2d进行交换.然后,我想添加一个RigiBody2D并在我的世界中显示该多维数据集.问题是我总是会收到错误:

I am creating a cube in script(c#). I want to remove the BoxCollider since i am developing a 2D game and exchange it through the BoxCollider2d. Then i want to add a RigiBody2D and show the cube in my world. The Problem is that i always get the error:

无法将组件'BoxCollider2D'添加到多维数据集,因为它与 现有的"BoxCollider"派生组件! UnityEngine.GameObject:AddComponent() CreateCube:OnCollisionEnter2D(Collision2D)(在 资产/脚本/CreateCube.cs:15)

Can't add component 'BoxCollider2D' to Cube because it conflicts with the existing 'BoxCollider' derived component! UnityEngine.GameObject:AddComponent() CreateCube:OnCollisionEnter2D(Collision2D) (at Assets/Scripts/CreateCube.cs:15)

我收到此错误,但代码仍然有效.但是它只会直到Destroy(cube.collider)行;就是这样! BoxCollider被正确地正确删除,原因是当我查看创建的对象时它已经消失了.我真的不知道为什么编译器会告诉我现有的BoxCollider.

I get this error but the Code works anyways. BUT it only goes till the line Destroy(cube.collider); and thats it! The BoxCollider is defenitly removed correctly cause when i take a look at the created objects it is gone. I really dont know why the compiler is telling me that there is a existing BoxCollider.

using UnityEngine;
using System.Collections;

public class CreateCube : MonoBehaviour
{
    void OnCollisionEnter2D(Collision2D coll)
    {
        // Create Cube
        GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);

        // Destroy BoxCollider
        Destroy(cube.collider);

        // Add BoxCollider2D
        cube.AddComponent<BoxCollider2D>();

        // Add RigiBody2D
        cube.AddComponent<Rigidbody2D>();

        // Show Cube in World
        cube.transform.position = new Vector3(0, 0.5f, 0);
    }
}

有人有主意吗?

推荐答案

Destroy将始终等到当前Update循环删除组件之后,因此在添加BoxCollider2D.改为使用DestroyImmediate.

Destroy will always wait until after the current Update loop to remove the component, so the Collider is not removed when you are adding the BoxCollider2D. Use DestroyImmediate instead.

但是,我建议使用所需的内容创建prefab,并改用Instantiate.像这样:

However I would recommend to create a prefab with the things you want and use Instantiate instead. Like this:

// Create Cube
GameObject cube = Instantiate(yourPrefab, new Vector(0, 0.5f, 0), Quaternion.identidy) as GameObject;

这篇关于在运行时添加/删除组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆