Collect Object from an Array C#

Hi

I’m still pretty new with C# (switching from unity script)

I have the following script in the scene, with a few collectibles that are placed in “collectibles” array in the inspector.

The script works, up to the point of the foreach - obviously I"m doing something wrong. I’m trying to destroy the collectible from the list when the player taps on it.

using UnityEngine;
using System.Collections;

public class TouchCollect : MonoBehaviour {


	public GameObject[] collectibles;
	private int _numberToCollect;


	void Start(){
		collectibles = GameObject.FindGameObjectsWithTag ("Collectible");
		_numberToCollect = collectibles.Length;
		Debug.Log ("Number to collect at start = " + _numberToCollect);
	}

	// Subscribe to events
	void OnEnable(){
		EasyTouch.On_TouchStart += On_TouchStart;

	}
	
	void OnDisable(){
		UnsubscribeEvent();
	}
	
	void OnDestroy(){
		UnsubscribeEvent();
	}
	
	void UnsubscribeEvent(){
		EasyTouch.On_TouchStart -= On_TouchStart;

	}


	// Simple tap
	private void On_TouchStart( Gesture gesture){

		foreach (GameObject collected in collectibles)
		// Verification that the action on the object
		if (gesture.pickObject == collected/*  RevealPickup.isShowing*/){
			Destroy(collected);
			_numberToCollect--;
			Debug.Log ("Number left to collect = "+_numberToCollect);
		}
	}
}

Any direction would be appreciated.
Thanks

What exactly isn’t working?

One problem you may have is that the array will still have a reference to the object after you destroy it. You want to “null” the reference after you destroy the object. I’m not sure what type of behaviour would happen if you keep references to destroyed objects around and then try destroying them again or comparing them to other objects. Probably nothing good.

And if you have nulls if your array, you need to check for that. If your gesture.pickObject ever returns a null, you could succeed on that conditional and then attempt to destroy a “null” (I’m not sure off-hand what would happen here either), and then you would incorrectly decrement your numberToCollect counter.

That’s a couple potential issues I can see just looking at that, but there may be something I missed. I would recommend writing a function that logs a complete state of your array (and the picked object) to the console and call it as the first and last thing you do in “On_TouchStart”. Then you should have a complete picture of exactly what you are doing to your array and the issues you are having should become obvious.