如何统一地摧毁一个物体



如何破坏统一中的对象?我知道你必须输入命令Destroy();但我想说的是,我不知道该在括号之间加什么。我尝试了很多不同的方法:公共GameObject电机;销毁(电机);但不起作用

using System.Collections;
using UnityEngine;
public class LogRotation : MonoBehaviour
{
[System.Serializable] //this will allow us to edit it in the editor
//a custom class representing a single rotation "element" of the log's rotation pattern
private class RotationElement
{
//to get rid of an obnoxious warning about these fields not being initialized
#pragma warning disable 0649
public float Speed;
public float Duration;
#pragma warning restore 0649
}
[SerializeField] //attribute making private fields editable in the Unity Editor
//the aforemention full rotation pattern of the log
private RotationElement[] rotationPattern;
//this will be set to the Wheel Joint 2D from the LogMotor object
private WheelJoint2D wheelJoint;
//something has to actually apply a force to the log through the Wheel Joint 2D
private JointMotor2D motor;
private void Awake()
{
//setting fields
wheelJoint = GetComponent<WheelJoint2D>();
motor = new JointMotor2D();
//starting an infinitely looping coroutine defined below right when this script loads (awakes)
StartCoroutine("PlayRotationPattern");
}
private IEnumerator PlayRotationPattern()
{
int rotationIndex = 0;
//infinite coroutine loop
while (true)
{
//working with physics, executing as if this was running in a FixedUpdate method
yield return new WaitForFixedUpdate();
motor.motorSpeed = rotationPattern[rotationIndex].Speed;
//hard coded 10000, feel free to experiment with other torques if you wish
motor.maxMotorTorque = 10000;
//set the updated motor to be the motor "sitting" on the Wheel Joint 2D
wheelJoint.motor = motor;
//let the motor do its thing for the specified duration
yield return new WaitForSecondsRealtime(rotationPattern[rotationIndex].Duration);
rotationIndex++;
//infinite loop through the rotationPattern
rotationIndex = rotationIndex < rotationPattern.Length ? rotationIndex : 0;
}
}
}

TLDRDestroy(motor.gameObject),但如果JointMotor2D不继承MonoBehaviour,则将不工作。


Destroy(obj)也可用于销毁组件
您需要将其引用到游戏对象以销毁它。

Destroy(GetComponent<RigidBody>())将从游戏对象中移除刚体,而不是移除对象本身。

Destroy(motor.gameObject)应该能做到这一点。

但一旦看到你的代码,它可能不会
因为看起来JointMotor2D不是MonoPhavior,也就是说它不存在于游戏世界中,所以你不能摧毁它。

根据您试图销毁的内容,您必须找到对它的引用。
最简单的方法是在检查器中引用它。或者摧毁自己,如果那已经是你想要摧毁的对象:

// Drag-drop the object in the inspector
[SerializeField] 
private GameObject toDestroyLater;
private void DestroyObject() {
Destroy(toDestroyLater);
// Destroys self
// (Aka, whatever game-object this script is attached to)
Destroy(this.gameObject);
}

最新更新