简体   繁体   中英

How can I enable one by one an array element(C#) Unity

This code is C# and I'm using the Unity game engine.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class CollisionDetectionForQuest : MonoBehaviour {

public GameObject[] Garbages;
public GameObject[] GarbagesDummy;
public bool activateInactive;
//public GameObject[] Counter;


void Start(){

    Garbages = GameObject.FindGameObjectsWithTag("Trash");
    foreach (GameObject garb in Garbages) {

    }

    GarbagesDummy = GameObject.FindGameObjectsWithTag ("TrashDummy");
    foreach(GameObject dummy in GarbagesDummy){
        dummy.gameObject.SetActive (false); 
    }
}

void OnCollisionEnter(Collision obj){
    if (obj.gameObject.CompareTag ("Trash")) {
        obj.gameObject.SetActive (false);
        activateInactive = true;

       //in this line i want to activate my GarbageDummy 1 by 1 base on
       //every Trash i put in my collider.
        foreach(GameObject a in GarbagesDummy){
            a.gameObject.SetActive (true);
        }
}

So basically I want to activate the garbagedummy gameobject 1 by 1 on every trash I put on my collider. But I tried this and it doesn't work:

foreach(GameObject dummy in GarbageDummy){
   for(int i = 0; i < GarbageDummy.Length; i++){
     dummy.gameobject.setActive(true);
  }
}

anyone help please.

Here is my screenshot:

这里

If you would like to activate a single garbage dummy object (any of them in the array), then you don't want to use a loop there. Instead, keep track of which one you've activated up to as a field like this:

public int ActivatedDummyIndex; // Add this!
public GameObject[] Garbages;
public GameObject[] GarbagesDummy;
...

Then whenever a trash object is added, increase that number and use it as an index in your GarbagesDummy array:

void OnCollisionEnter(Collision obj){
    if (obj.gameObject.CompareTag ("Trash")) {
        obj.gameObject.SetActive (false);
        activateInactive = true;

        // Get the next dummy:
        GameObject dummy = GarbagesDummy[ActivatedDummyIndex];

        // Increase the index for next time:
        ActivatedDummyIndex++;

        // Activate that dummy:
        dummy.SetActive(true);
    }
}

This assumes that the number of dummy objects is the same as the number of trash objects. If you've got more trash objects and add them all, you'll eventually get an index out of range exception (as it would "run out" of dummy objects to use).

Whilst that should answer your question, it's worth mentioning that this isn't the typical approach . Rather than having a fixed number of hidden dummy objects and showing one when needed, you'd normally instance a new dummy object instead (using GameObject.Instantiate ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM