【问题标题】:C# Coding Issue with Randomized Auto Spawns随机自动生成的 C# 编码问题
【发布时间】:2017-10-22 17:49:29
【问题描述】:

我在使用 C# 使用 Unity/MonoDevelop 进行编码时遇到了一些问题。我想要做的是有 30 个不同的位置,但是使用随机发生器只有 20 个位置会生成一个预制件。我正在使用有关生成对象的 Youtube 频道 Gamad 教程 (https://www.youtube.com/watch?v=kTvBRkPTvRY) 修改脚本。 以下是我目前拥有的: `使用 System.Collections; 使用 System.Collections.Generic; 使用 UnityEngine;

公共类 SpawnObject : MonoBehaviour { public GameObject BeehivePrefab;

public Vector3 center;
public Vector3 size;

public Quaternion min;
public Quaternion max;

public int spawnCount = 0;
public int maxSpawns = 20;
public GameObject [] selectorArr;

// Use this for initialization
void Start () {
    SpawnBeehive ();
}

// Update is called once per frame
void Update () {
    while (spawnCount < maxSpawns){
        int temp = Random.Range(0, selectorArr.length);
        selectorArr[temp].Instantiate;
        spawnCount++;
    }
}

public void SpawnBeehive(){
    Vector3 pos = center + new Vector3 (Random.Range (-size.x / 2, size.x / 2),Random.Range (-size.y / 2, size.y / 2), Random.Range (-size.z / 2, size.z / 2));

    Instantiate (BeehivePrefab, pos, Quaternion.identity);
}

void OnDrawGizmosSelected(){
    Gizmos.color = new Color (1, 0, 0, 0.5f);
    Gizmos.DrawCube (transform.localPosition + center, size);
}

}` 在这段代码中,我在第 26 行和第 27 行(带有 int tem 和 selectorArr 的行)出现错误。

【问题讨论】:

    标签: c# unity5 monodevelop


    【解决方案1】:

    我以前从未使用过 GameObject.Instantiate 函数,我通常只是实例化对象或通过代码更改对象的渲染。但是从文档页面docs.unity3d.com/ScriptReference/Object.Instantiate.html 看来,它似乎允许您克隆一个对象

    我对你有 GameObject Array selectorArr 的用途有点困惑。

    现在,如果您想要生成一组不同的对象,您可以使用类似的方法。

    Instantiate(selectorArr[temp], Vector3, Quaternion.identity);
    

    或者,如果你想在一个区域内保持随机性,你可以通过类似这样的方式重复使用该函数,然后调用 SpawnBeehive( WhatEverGameObjectYouWant )

    public void SpawnBeehive(GameObject foobar){
        Vector3 pos = center + new Vector3 (Random.Range (-size.x / 2, size.x / 2),Random.Range (-size.y / 2, size.y / 2), Random.Range (-size.z / 2, size.z / 2));
    
        Instantiate (foobar, pos, Quaternion.identity);
    }
    

    【讨论】:

    • 还有 selectorArr.Length
    • 我不是世界上最好的程序员,但我非常感谢您的帮助。如果我可以问它会是什么参数?像vector3 x,y,z?
    • 抱歉,之前没有时间输入正确答案。希望这会有所帮助
    • 不用担心,至于“混乱”部分,我很抱歉,这是我试图使用一些统一手册中的代码来复制的东西。
    猜你喜欢
    • 1970-01-01
    • 2017-04-10
    • 2011-05-18
    • 2013-10-21
    • 2023-04-02
    • 1970-01-01
    • 2011-05-19
    • 2018-08-30
    • 1970-01-01
    相关资源
    最近更新 更多