【问题标题】:How to add game objects in GameObjects array from c# code?如何从 C# 代码在 GameObjects 数组中添加游戏对象?
【发布时间】:2021-09-08 06:47:50
【问题描述】:

我的 C# 脚本中有一个数组

GameObjects[] gameObjects

我有一个对象

GameObject myObject

我想在 gameObjects 数组中创建随机数量的元素并将 myObject 添加到数组的每个元素(我的对象可以是立方体、球体或任何东西),然后在屏幕上实例化它。我该怎么做?

我下面已经有代码了

public GameObject[] myObjects;

void Start()
{
    float x = gameObject.GetComponent<Camera>().transform.position.x - Random.Range(100, 200);
    float y = gameObject.GetComponent<Camera>().transform.position.y - Random.Range(50, 150);
    float z = gameObject.GetComponent<Camera>().transform.position.z + 800;
    Instantiate(myObjects[0], new Vector3(x, y, z), Quaternion.identity);
}

它工作得很好,但是使用这段代码,我只能从统一属性将对象添加到数组中,但我需要从代码中添加元素。我在互联网上没有找到任何关于它的信息。

【问题讨论】:

标签: c# arrays unity3d


【解决方案1】:

似乎list 可能更适合您的需求。

如果必须使用数组,可以在Start()方法上初始化数组的大小。

public GameObject[] myObjects;

const int maxSize = 20;
const int minSize = 1;

void Start()
{

    int arraySize = Random.Range(minSize, maxSize);
    myObjects = new GameObject[arraySize];

    for (int i = 0; i < arraySize; i++)
    {
        // Be sure to change the positions of each object
        float x = gameObject.GetComponent<Camera>().transform.position.x - Random.Range(100, 200);
        float y = gameObject.GetComponent<Camera>().transform.position.y - Random.Range(50, 150);
        float z = gameObject.GetComponent<Camera>().transform.position.z + 800;
        Instantiate(myObjects[i], new Vector3(x, y, z), Quaternion.identity);
    }
}

【讨论】:

  • 非常感谢!你的代码不是我真正需要的,但多亏了你,我明白我做错了什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-27
  • 1970-01-01
  • 2022-11-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多