The thing that happens is that these objects will get destroyed and i want to do something once one of these gameObjects becomes null and gets removed from the array. I want to it detect if an element from just this array has been destroyed and then i want to do something (increasing an int by 1 for example).
I figure since this is happening during game time it has to be updated when an element has been removed from the array so i will need to loop through the array to see if the index of it has been decreased by a certain amount. How will i go about doing this the correct but most simplest way (not that good with unity and c#).
I would use a property (the equivalent of a getter & setter in another programming language)
// C#
// Note : I haven't tested this code, I wrote it in a simple Notepad, do not hesitate to tell me if there is an error.
private GameObject[] battleshipAmount ;
public GameObject[] BattleshipAmount
{
get { return battleshipAmount ; }
set
{
if( battleshipAmount == null )
{
battleshipAmount = value ;
return ;
}
if( battleshipAmount.Length > value.Length )
{
// A GameObject has been destroyed
// Check which gameobject has been destroyed
for( int i = 0 ; i < battleshipAmount.Length ; ++i )
{
for( int j = 0 ; j < value.Length ; ++j )
{
// Check if gameobject is in the new array
if( battleshipAmount*.GetInstanceID() == value[j].GetInstanceID() )*
{ // GameObject still here continue ; } } // If this part of the code is reached, a destroyed gameobject has been found Debug.Log( “The gameobject #” + i + " has been destroyed!" ) ; } } else if( battleshipAmount.Length < value.Length ) { // A GameObject has been added } battleshipAmount = value ; } } Then, in your code, never use battleshipAmount, but use BattleshipAmount instead (notice the capital letter). BattleshipAmount can be use in the exact same way you would use battleshipAmount.
You can also use an event-based approach to not rely on a loop each time a battleship is destroyed.
Basically, you’d have a script on each battleship which contains the following:
Action <BattleshipScript> DestroyShip;
From your script that handles the changes (you mentioned an int that will increase, for example) you would then subscribe to this action.
Before a ship is destroyed, call DestroyShip(this) and it will execute all methods that have been subscribed to that particular ship. This allows for more control and less polling, no loops etc.
Unfortunately i cannot provide a code sample as it is not exactly clear what you already have, but this will only need a couple of lines to set up, probably not more than 3-4.