微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

脚本将对象移动到错误的位置

如何解决脚本将对象移动到错误的位置

我有一个脚本来替换其损坏的预制件上的对象,并将它们称为位置和旋转(随机)。它可以完美地与单个对象一起使用,但是如果我使用此脚本添加一个对象,它将在第一个对象的位置生成“ whackedPrefab”。

代码

using System.Collections.Generic;
using UnityEngine;

public class whackReplacer : MonoBehavIoUr
{
    public GameObject whackPrefab;
    private float[] rotateVectors = { 0f,90f,180f}; 
    private float randomVector;
    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Destroyer"){
            
            Debug.Log("I collided with: "+collision.gameObject.name);
            Instantiate(whackPrefab);           
            whackPrefab.transform.position = new Vector3(this.gameObject.transform.position.x,this.gameObject.transform.position.y,this.gameObject.transform.position.z);
            randomVector = rotateVectors[Random.Range(0,rotateVectors.Length)];
            whackPrefab.transform.rotation = new Quaternion(0f,this.gameObject.transform.rotation.x,randomVector+this.gameObject.transform.rotation.y,this.gameObject.transform.rotation.z);
            Destroy(gameObject);            
    }
    }
}

解决方法

使用Instantiate(对象原始,Vector3位置,四元数旋转)轻松修复;

这是解决方案:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class whackReplacer : MonoBehaviour
{
    public GameObject whackPrefab;
    private float[] rotateVectors = { 0f,90f,180f}; 
    private float randomVector;
    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Destroyer"){           
            Debug.Log("I collided with: "+collision.gameObject.name);
            randomVector = rotateVectors[Random.Range(0,rotateVectors.Length)];
            Instantiate(whackPrefab,new Vector3(this.gameObject.transform.position.x,this.gameObject.transform.position.y,this.gameObject.transform.position.z),new Quaternion(0f,this.gameObject.transform.rotation.x,randomVector+this.gameObject.transform.rotation.y,this.gameObject.transform.rotation.z));         
            Destroy(gameObject);            
    }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。