首页 > 解决方案 > 生成的对象未销毁问题

问题描述

我有一个小问题,我有一个附加类的对象。在这个类中,我有一个 Enum ... ,它决定了我想要创建的对象的类型。问题是当我开始游戏然后我停止它时,会创建另一个对象并且它不会破坏另一个对象。每次开始和停止游戏时,都会创建另一个对象。整个问题出在 Update 方法中。 想像

using EduUtils.Events;
using EduUtils.Visual;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class TrainCell : ObjectSequence
{
public Transform[] Obstacles;
public bool used = false;
public bool hasRail = false;
public bool underBuilding = false;
public bool underTrain = false;
public bool hasObstacle = false;
[HideInInspector] public int oldIndex = 0;
public enum ShapeObstacleType
{
    NONE,
    ROCK,
    TREE
}

public ShapeObstacleType currentObstacleType;
private ShapeObstacleType oldObstacleType = ShapeObstacleType.NONE;

private Transform currentObstacle;

private new void Update()
{
    if (Application.isEditor && !Application.isPlaying)
    {
        if (currentObstacleType != oldObstacleType)
        {
            oldObstacleType = currentObstacleType;
            if (currentObstacle != null)
            {
                hasObstacle = false;
                DestroyImmediate(currentObstacle.gameObject);
            }
            if (currentObstacleType != ShapeObstacleType.NONE)
            {                   
                currentObstacle = Instantiate(Obstacles[(int)currentObstacleType - 1]);
                currentObstacle.transform.parent = transform;
                currentObstacle.transform.localPosition = Vector3.zero;
                hasObstacle = true;
            }
        }
        if (currentObstacle == null)
            hasObstacle = false;         
    }
}

}

此代码在编辑模式下执行......如果我在创建对象之前检查,这就是问题所在。检查它是否不为空,然后将其销毁。非常感谢。

标签: c#unity3d

解决方案


我发现了问题....这个:

private ShapeObstacleType oldObstacleType = ShapeObstacleType.NONE; 这必须是公开的。我不知道为什么,但我认为 [enum] 不会改变他的类型,如果他是私人的。如果它是私有的以及为什么它公开,我无法解释为什么它不起作用。我会记录自己并回来解释,或者如果其他人已经有了解释。谢谢!


推荐阅读