【发布时间】:2015-05-20 18:32:04
【问题描述】:
我想在一个特定的圆形区域内销毁一个对象的实例。代码如下:
Collider2D[] overlap = Physics2D.OverlapCircleAll(
ball.transform.position,
(ball.renderer.bounds.size.x)/2);
if (overlap.Length>=1)
{
foreach (Collider2D coll in overlap)
{
Debug.Log (coll.GetInstanceID());
if (coll.name.Contains("alien"))
{
//problem here:
Destroy (coll.gameObject);
}
}
}
Destroy(coll.gameObject) 永久销毁所有克隆,新的没有实例化,我收到错误 MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
有没有办法专门销毁那个和那个克隆?我尝试了不同的名称并使用了Destroy(GameObject.Find(coll.name)),但这也会破坏所有克隆并阻止新的生成。
有人帮忙吗?
更新:
实例化如下:
private bool bCanCreateParachuter = true; // bool to stop the spawning
GameObject go;
// Use this for initialization
void Start () {
//handling screen orientation
Screen.orientation = ScreenOrientation.LandscapeLeft;
///
go = (GameObject)Instantiate(Resources.Load("alienPink"));
StartCoroutine("CreateParachuter");
}
IEnumerator CreateParachuter()
{
while(bCanCreateParachuter)
{
Instantiate(go, new Vector3(Random.Range(-10,10), Random.Range(-5,5), 0), Quaternion.identity);
// Instantiate(go, new Vector3(Random.Range(-10,10), Random.Range(-10,10), 0), Quaternion.identity);
go.name = "alienPink"+nextNameNumber;
nextNameNumber++;
yield return new WaitForSeconds(Random.Range(0f,1f));
yield return null;
}
yield return null;
}
重要更新:
如果我在中取消注释 if (grabbedObject !=null),则代码有效
// if (grabbedObject != null) {
//works if uncomment above for some reason
Collider2D[] overlap = Physics2D.OverlapCircleAll (ball.transform.position, (ball.renderer.bounds.size.x)/2);
if (overlap.Length>=1){
foreach (Collider2D coll in overlap){
Debug.Log (coll.GetInstanceID());
if (coll.name.Contains("alien")){
Destroy (coll.gameObject);
}
}
}else {
// Debug.Log (grabbedObject.renderer.bounds.size.x);
}
这是grabbedObject的背景:
Rigidbody2D grabbedObject = null;
. . .
RaycastHit2D hit = Physics2D.Raycast(mousePos2D , dir);
//if (hit!=null && hit.collider!=null){
// check collisions with aliens
// OnCollisionEnter2D(grabbedObject.collisionDetectionMode);
if ( hit.collider!=null){
// we clicked on something lol... something that has a collider (box2d collider in this case)
if (hit.collider.rigidbody2D!=null){
//hit.collider.rigidbody2D.gravityScale = 1;
grabbedObject = hit.collider.rigidbody2D;
// circleCollider = hit.collider.collider2D. ;
springJoint = grabbedObject.gameObject.AddComponent<SpringJoint2D>();
// set the anchor to the spot on the object that we clicked
Vector3 localHitPoint = grabbedObject.transform.InverseTransformPoint(hit.point);
springJoint.anchor = localHitPoint;
//
dragLine.enabled = true;
}
}
基本上,grabbedObject 是您在屏幕上单击并拖动的任何东西(任何游戏对象),我在这里错过了什么?
【问题讨论】:
-
你如何创建
gameObject的克隆? -
您的“克隆”代码可能有问题...或
Destroy- 确保发布尽可能少的代码集,显示所有相关部分都存在问题。 -
更新了原始帖子以包括实例化
-
我不知道安德鲁会有什么成就..
标签: c# unity3d game-engine