How to fix : The object of type 'GameObject' has been destroyed but you are still trying to access it ? -Unity - unity3d

I made a 5 second time bar to replace the wave. when wave1 has been 5 seconds it will move to wave2. then the first wave will be destroyed. when I got to wave3, an error came out. here's my code:
IEnumerator ChangeWave()
{
for (int i = 0; i < wave.Length - 1; i++)
{
yield return new WaitForSeconds(5f);
Destroy(wave[i]);
wave[i+1].SetActive(true);
}
}
the error said The object of type 'GameObject' has been destroyed but you are still trying to access it. - unity
sorry for my bad english.

There's a few things going on here.
Remove the -1 in the for loop, so it iterates to end
wave[i+1] will cause an error, so check if (i < wave.Length -1)
Destroy( array[index] ) will try and access Game Object but it's destroyed, so you should create a temporary var to hold gameobject, and set null to the array element.
Some fixes below - there might be a better way, but this is what I use:
Version 1 - Using the above fixes
IEnumerator ChangeWaveV2()
{
for (int i = 0; i < wave.Length; i++)
{
yield return new WaitForSeconds(.2f);
var t = wave[i];
wave[i] = null;
Destroy(t);
if(i < wave.Length - 1)
wave[i + 1].SetActive(true);
}
}
Version 2 - A variation without needing to null out the element and create a temporary var. If you iterate from end to front of the array, you can freely Destroy() GameObjects in an array. May not be useful as it changes the wave array.
IEnumerator ChangeWaveV3()
{
System.Array.Reverse(wave);
for (int i = wave.Length - 1; i >= 0; i--)
{
yield return new WaitForSeconds(.2f);
Destroy(wave[i]);
if(i > 0)
wave[i - 1].SetActive(true);
}
}

Related

How to print only unique names here in photon network unity

I did this but it prints one name multiple times. How do I make sure it prints one name only one at a time:
foreach(Player player in PhotonNetwork.PlayerList)
{
if(race_entered)
{
for(int i = 0; i <= PhotonNetwork.PlayerList.Length; i++)
{
player_name[i].text = player.NickName;
}
}
}
You are currently iterating exponentially. For every player you again iterate all players and overwrite all UI texts with the current player.
What you want is iterating only once
if(race_entered)
{
// cache since property access might be expensive
var players = PhotonNetwork.PlayerList;
// Note btw for iterating collections you always want an index
// "< Length" instead of "<= Length"
for(int i = 0; i < players.Length; i++)
{
var player = players[i];
player_name[i].text = player.NickName;
}
}

toarray function dont updated outside the blocks

I try to change an array of user in my mongodb from another collection.
this is the code:
phrases.find({albumID: tileid}).toArray(function(err, results) {
if (results.length > 0) {
for(var j = 0; j < results.length; j++)
{
for(var z = 0; z < o.Phrases.length; z++)
{
if(o.Phrases[z].id == results[j]._id)
{
o.Phrases.splice(z,1);
break;
}
}
}
}
});
console.log(o.Phrases);
.
.
.
after update the collection
When I do logs, I don't see the change being made.
If I do the logs in toArray blocks, I see the changes.
I read alot, And dont found solution only that toArray is async function but not how to change it or to use it.
Maybe there is another way to change the collection to the array.
thanks for helping.

Linked List Parameterized constructor

I tried to do a Parameterized constructor for a linked list my program is about to implement a queue by using a liked list so i want to do a parameterized constructor like Queue(int value , int size) and it dose not run or doing a list
this is my code for this problem
Queue(int value,int _size)
{
for(int i = 0; i < _size; ++i)
{
Node* temp = new Node;
temp->data = value;
temp->next = nullptr;
if(head == nullptr)
{
head = tail = temp;
}
else
{
tail->next = temp;
tail = temp;
}
}
}
i expected that the result is to fill the lest by value times size like if i run this function Queue x(20,3) the linked list should be
20 20 20
Since that this is a constructor, The head and tail are not properly initialized to use them. I would suggest adding head = tail = nullptr just before the loop and see what happens.
Follow this code after your node creation. I hope this will work. And do use i++ instead of ++i, as the later will make the loop for size-1 times.
if(head == NULL)
head = temp;
else{
Node *x;
x= head;
while(x->next != NULL)
x = x->next;
x->next = temp;
}

Unity / Search closes Object from a List by tag

I have a Problem to find the closest Object in my List.
There are three types with the tags (Food, Stone and Wood).
I spawn them at the beginning , some for each type, if i found some Resources, they're not hidden anymore, and i add them to the List that a Worker goes to them and harvests them.
So Later in the Game, for expample
i found 3 Stone Resources, then worker should harvest the closest one first everytime....
but i don't know how to iterate throw a Loop only to search for the Tags and how to get the position of the closest one.
Here is some code of the Method that i wrote:
void FindNearestFoodRessource()
{
for (int i = 0; i < gameController.discoveredRessources.Count; i++)
{
//float dist = Vector3.Distance(gameController.discoveredRessources[i].transform.position, transform.position);
GameObject nearestFoodRessource = GameObject.FindGameObjectWithTag("Food");
}
}
First thing first - don't use FindGameObject**** in frequently called methods, it is very expensive.
About your problem - just check tag and distance of all the resources:
float minDist = Vector3.Distance(gameController.discoveredRessources[0].transform.position, transform.position);
int minDistIndex = 0;
for (int i = 1; i < gameController.discoveredRessources.Count; i++)
{
if (gameController.discoveredRessources[i].gameObject.CompareTag("Food"))
{
float dist = Vector3.Distance(gameController.discoveredRessources[i].transform.position, transform.position);
if (dist < minDist)
{
minDist = dist;
minDistIndex = i;
}
}
}
//Now you can move to gameController.discoveredRessources[minDistIndex]
Also you can store all the food/stones/wood in the separate lists when you find it
Using Linq Where and this usefull extension method MinBy
using System;
using System.Collections.Generic;
using System.Linq;
public static class Linqextensions
{
public static T MinBy<T, R>(this IEnumerable<T> en, Func<T, R> evaluate) where R : IComparable<R>
{
return en.Select(t => new Tuple<T, R>(t, evaluate(t)))
.Aggregate((max, next) => next.Item2.CompareTo(max.Item2) < 0 ? next : max).Item1;
}
}
(simply copy that code somwhere into your project) you could do it in "one" line
var closestItem = gameController.discoveredRessources
// this is a filter only selecting the ones with tag = "Food"
.Where(obj => obj.CompareTag("Food"))
// this returns you the item from the list with the lowest distance
.MinBy(obj => Vector3.Distance(obj.transform.position, transform.position));

Access non static function from static function

Here is some insight: I am working with UnityScript in Unity 4.6.3. I have one script called Pause.js and it contains this function:
function fadeMusicOut () {
while (audio.volume >= 0.005) {
yield WaitForSeconds(0.1);
Debug.Log("Loop Entered: " + audio.volume);
audio.volume = (audio.volume - 0.015);
}
Another script GameManager.js has this function:
static function Score (wallName : String) {
if (wallName == "rightWall") {
playerScore01 += 1;
}
else {
playerScore02 += 1;
}
if (playerScore01 == SettingsBack.scoreLimit || playerScore02 == SettingsBack.scoreLimit)
{
startParticles = 1;
SettingsBack.gameOver = 1;
BallControl.fadeSound = 1;
yield WaitForSeconds(4);
Camera.main.SendMessage("fadeOut");
Pause.fadeMusic = 1;
SettingsBack.soundVolume = 0;
yield WaitForSeconds(2);
playerScore01 = 0;
playerScore02 = 0;
SettingsBack.soundVolume = oldSoundVol;
Application.LoadLevel("_Menu");
}
}
So pretty much I want to call the fadeMusicOut() function from static function Score, but it will not let me because it says it needs an instance of that object.
The Pause.js script is not attached to any game objects, but it is attached to 2 buttons that call their specific functions. The GameManager.js script is attached to an object called GM. So how can I go about calling fadeMusicOut() from the Score function?
I have tried setting new vars that import the game object but still no luck. I tried making fadeMusicOut() a static function, but it creates many errors.
Any help at all is appreciated.