【问题标题】:Script moves object in wrong place脚本将对象移动到错误的位置
【发布时间】:2020-11-01 16:02:10
【问题描述】:

我有一个脚本可以替换他被破坏的预制件上的对象,并将它们称为位置和旋转(带有一些随机)。它完美地适用于单个对象,但如果我使用此脚本添加另一个对象,它会在第一个对象的位置生成“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);            
    }
    }
}

【问题讨论】:

    标签: c# unity3d game-development


    【解决方案1】:

    使用 Instantiate(Object original, Vector3 position, Quaternion rotation) 轻松修复;

    这是解决方案:

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

    【讨论】:

      猜你喜欢
      • 2018-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多