Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

c# - Spawning random GameObject in map (no repetitions)

Im making a terror game, and i want to spawn little collectibles in my scene, my code works fine, but they repeat the world location in every instantiate:

using UnityEngine;

public class objectivesGeneration : MonoBehaviour
{
    GameObject[] objSpawn;
    GameObject objActual;
    public GameObject obj;
    int index;
    void Start()
    {
        objSpawn = GameObject.FindGameObjectsWithTag("spawnObj");
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.I))
        {
            generateNewObj();
        }
    }

    public void generateNewObj()
    {
        index = Random.Range(0, objSpawn.Length);
        objActual = objSpawn[index];
        createObj();
    }
    public void createObj()
    {
        
        Instantiate(obj, objActual.transform.position, objActual.transform.rotation);
    }
}

Can somebody help me?

question from:https://stackoverflow.com/questions/65713832/spawning-random-gameobject-in-map-no-repetitions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your question can be understood in two ways. Leoverload gave the answer to the repeating position. In case you do not want to repeat the same type of object (so all objects are unique), then do the following:

  1. Turn objSpawn into a List<GameObject> variable and in the start() function, add all instances from the array that's returned from FindGameObjectsWithTag to it.
  2. Turn objSpawn.Length into objSpawn.Count (which does the same but for lists) In that same function add: objSpawn.Remove(objActual) at the end. If those objects are destroyed at some point and you want to create new instances of destroyed objects, ensure that in their Destroy event, you Add(gameObject) to the list again.

Am giving you instructions instead of just code so you can learn to do this yourself in the future.

Also I have the feeling you need to learn how argumentsparameters work. Then you can ommit that objActual variable and instead pass the object to createObj(GameObject theObj) directly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...