1
votes

I am having some issues with coding with Unity/MonoDevelop using C#. What I am trying to do is have 30 different locations, however using a randomizer only 20 of those locations will spawn a prefab. I am modifying the script using the Youtube Channel Gamad tutorial on spawning objects (https://www.youtube.com/watch?v=kTvBRkPTvRY). below is what I presently have: `using System.Collections; using System.Collections.Generic; using UnityEngine;

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

}` In this code I am getting errors on Lines 26 and 27 (lines with int tem and selectorArr).

1

1 Answers

1
votes

I've never used the GameObject.Instantiate function before, I normally just Instantiate objects or change the render of the object through code. But from the document page docs.unity3d.com/ScriptReference/Object.Instantiate.html it seems to allow you to clone an object

I'm a little confused as to what you have the GameObject Array selectorArr for.

Now if it's an array of different objects you want to spawn you can do it with something like.

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

Or if you want to keep the random within an area you can re-use the function with something like this, and just call 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);
}