Do a function if the named GameObject has 1 or more clones

Im trying to make a condition which let any function if there is 2 or more gameobjects with a certain name. However, im learning how to script, and i couldnt find any solution. (Excuse me for my english)

Well, this is easier to solve if we have more info. One thing is, how are these gameobjects being generated? For example, if I instantiate stuff, let’s say I have a creature generator and it spits out orcs and trolls. I could simply keep a running tally of what gets picked if I’m doing a random selection. Then if something dies, I just subtract from it’s total. If I need to run a script I can trigger a loop or the script once I have 2 or more and have it run as long as that requirement is met.

But again, you have to give some context to what you are doing to know if this would work for you or not.

(You could also maintain a gameobject list of all trolls for example and do a count on the list to see if it’s 2 or greater. Then just remove the troll from the list when it dies)

Sorry

What im trying to do is to have one dontdestroyfromload object. I got a gameobject with this script inside, which, at the start ,it passes to DontDestroyOnLoad. However, everytime i reload the scene with this GameObject, it gets duplicated. What i want to do is, in Start function, add a condition that if theres a clone, it removes one of these gameobjects (or the cloned one)

In that case, I think this is what you want. I added a few short comments to help illustrate.

public static YourClass Instance;

void Awake(){
   // if there is no instance/copy at all.
   if(Instance == null){
      instance = this;
      DontDestroyOnLoad(gameObject);
   }
   // If it already exists, but this copy isn't it..
   else if(instance != this){
      Destroy(gameObject);
   }
}
1 Like

It works perfectly! Thanks you!!

You’re welcome :slight_smile:

This structure is called a singleton if you need to google more information and examples.