简体   繁体   English

C#/ Unity实例化多个GameObject并将其position.x +1

[英]C# / Unity Instantiate multiple GameObjects and move their position.x by +1

i have a code that spawns random amount of coins, but the problem is that they are spawning inside each other. 我有一个生成随机数量硬币的代码,但是问题是它们彼此内部生成。

What i want is to have a line of coins, not just one that has like 3 spawned in it. 我想要的是有一排硬币,而不仅仅是其中产生了3枚硬币。

I tried to get the current x position of the current object that spawned and added +1 to its x cord, so that the next object spawns +1 to x cord. 我试图获取生成的当前对象的当前x位置,并为其x线添加+1,以便下一个对象生成x线的+1。

        private void SpawnCoin()
{
    coinSpawn = Random.Range(1, 5);

    for (int i = 0; i < coinSpawn; i++)
    {
        spawnCoin = Instantiate(coin) as GameObject;
        spawnCoin.transform.SetParent(transform);
        float currentPos = spawnCoin.transform.position.x;
        //spawnCoin.transform.Translate(currentPos+1f, -0.1f, -1f);
    }

}

I think there must be something with the Parent's transform that changes it back to 0? 我认为Parent的转换中一定有将其更改回0的东西吗?

Also the coins are moving in the x cordinate: 硬币也在x坐标中移动:

    // Use this for initialization
void Start () {
    transform.Translate(0f, -0.1f, -1f);
}

// Update is called once per frame
void Update () {
    transform.Translate(0f - Time.deltaTime * BackgroundScroll.speed, 0f, 0f);
}

Edit: I know that //spawnCoin.transform.Translate(currentPos+1f, -0.1f, -1f); 编辑:我知道//spawnCoin.transform.Translate(currentPos+1f, -0.1f, -1f); this changes the current spawned coins transform, thats why i commented it, but i want to change the upcoming ones. 这改变了当前生成的硬币变换,这就是为什么我评论了它,但是我想改变即将到来的硬币。

Try: 尝试:

private void SpawnCoin()
{
     coinSpawn = Random.Range(1, 5);
     float x = 1.0f;
     for (int i = 0; i < coinSpawn; i++)
     {
         spawnCoin = Instantiate(coin) as GameObject;
         spawnCoin.transform.SetParent(transform);
         float currentPos = spawnCoin.transform.position.x;
         spawnCoin.transform.Translate(currentPos+x, -0.1f, -1f);
         x+=1.0f;
     }

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM