Unity C#,产生错误位置的对象

问题描述 投票:0回答:2

我试图在Y轴上逐个产生+0.6空间的对象。对象应该是0.6,1.2,1.8,2.4,3等,而它看起来像0.6,1.8,3.6,6,9等。我不知道发生了什么,所以我希望你能帮助我,这是一个代码:

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

public class Spawner : MonoBehaviour {

public GameObject cubeOne, cubeDouble, cubeTriple, cubeQuattro, cubeOneShort, cubeDoubleShort, cubeTripleShort, cubeQuattroShort, sphereOne, sphereDouble, sphereTriple, sphereQuattro, sphereOneShort, sphereDoubleShort, sphereTripleShort, sphereQuattroShort;
int whatToSpawn;
float position;
int yRotation;

void Update () {

        whatToSpawn = Random.Range(1, 5);
        position += 0.6f;
        Vector3 newPosition = transform.position;
        newPosition.y += position;

        switch (whatToSpawn)
        {
            case 1:
                Instantiate(cubeOne, transform.position = newPosition, transform.rotation * Quaternion.Euler(90, 0, 0));
                Debug.Log(position);
                break;
            case 2:
                Instantiate(cubeDouble, transform.position = newPosition, transform.rotation * Quaternion.Euler(90, 0, 0));
                Debug.Log(position);
                break;
            case 3:
                Instantiate(cubeTriple, transform.position = newPosition, transform.rotation * Quaternion.Euler(90, 0, 0));
                Debug.Log(position);
                break;
            case 4:
                Instantiate(cubeQuattro, transform.position = newPosition, transform.rotation * Quaternion.Euler(90, 0, 0));
                Debug.Log(position);
                break;
        }
   }
}

谢谢你的回答。

c# object unity3d spawn
2个回答
5
投票

假设您正在尝试使用Instantiate重载public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);

Instantiate中的代码正在移动spawner的transform.position。将实例化代码更改为:

Instantiate(cubeOne, newPosition, transform.rotation * Quaternion.Euler(90, 0, 0));

2
投票

您将position添加到newposition并每次将position增加0.6并将其分配给产卵对象。所以我看到的是这样的:

 loops  |  position | newposition |  p + np  =  result
-------------------------------------------------------
      1 |     0.6   |      0      |  0+0.6   =  0.6
             +0.6           .-------------------↵
               ↓           ↓
      2 |     1.2   |     0.6     |  1.2+0.6 =  1.8
             +0.6           .-------------------↵
               ↓           ↓
      3 |     1.8   |     1.8     |  1.8+1.8 =  3.6

等等...

所以我认为这只是数学上的。因此Fish提出的解决方法。

© www.soinside.com 2019 - 2024. All rights reserved.