生成的对象没有被销毁的问题

时间:2019-08-07 12:24:07

标签: c# unity3d

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

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;         
    }
}

}

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

1 个答案:

答案 0 :(得分:0)

我发现了问题...。

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