dimanche 30 avril 2017

Unity c#: How to prevent same object from being picked from array twice in a row

Good Afternoon all.

I am having a bit of a problem figuring out how to randomly get an object out of a list that wasn't picked on the last update of a script. When this randomly instantiated object is spawned and reaches a certain y value, it will set itself to inactive. So when this object is not active, it will go through an array and pick another object at random. However, I do not want to include the previous active object.

example: blue ball was first active. Moves on the Y axis. Becomes inactive. Next object spawn should have no chance of being a blue ball. Any ideas and help will be greatly appreciated.

My code is below

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ballGeneratorShooter : MonoBehaviour
{

    private int ballSelector;
    private TagNumber theTagNumber;
    public ObjectPooler[] theObjectballPools;//In my inspector, I have 5 prefab gameObjects attached
    List<ObjectPooler> changingBalls;

    public bool changeBalls;

    public GameObject currentBall;
    public GameObject newBall;

    // Use this for initialization
    void Start()
    {

        changingBalls = new List<ObjectPooler>();
        currentBall = newBall;
    }

    // Update is called once per frame
    void Update()
    {

        if (newBall == null)
        {

            ballSelector = Random.Range(0, theObjectballPools.Length);

            newBall = theObjectballPools[ballSelector].GetPooledObject();

            newBall.transform.position = transform.position;
            newBall.transform.rotation = transform.rotation;
            newBall.SetActive(true);
        }

        if (newBall.activeInHierarchy == false)
        {
            if (changeBalls)
            {
                for (int i = 0; i < theObjectballPools.Length; i++)
                {
                    if (theObjectballPools[i].GetPooledObject().GetComponent<TagNumber>().tag != currentBall.GetComponent<TagNumber>().tag)
                    {
                        changingBalls.Add(theObjectballPools[i]);
                    }
                    //changingballs.Add(theObjectballPools[i]);
                }

                ballSelector = Random.Range(0, changingBalls.Count);
                newBall = theObjectballPools[ballSelector].GetPooledObject();
                Debug.Log(changingBalls.Count);
                newBall.transform.position = transform.position;
                newBall.transform.rotation = transform.rotation;
                newBall.SetActive(true);
                currentBall = newBall;
                changeBalls = false;
                changingBalls.Clear();
            }

        }

    }

}




Aucun commentaire:

Enregistrer un commentaire