About cloned scripts

Hi. I’m stuck on this problem for a while. Could someone help pls.
I have a prefab which I clone a few a times on startup. After that I want to choose a random one and run the script inside of it but I don’t know how to. Every time I want to access that specific script it just strats running in all of the clone instances. How can I access that particular script without triggering the others which I guess all have the same name.

There is not a lot of info here, so I have made some assumptions.

  • In the prefab, whatever script you have inside it, don’t put the code you want to run inside the start method (anything in start or awake gets run as the object is created and enabled). Put it in a separate method, and name it appropriately (for arguments sake, lets call it DoSomething())
  • Create a ‘controller’ class in your project.
  • Use this to initiate and control the ‘cloning’ of your prefabs. (Resources.Load())
  • As you clone each prefab, use GetComponent() to get a reference to its script.
  • Store this in a Dictionary or a List (Or you could store a reference to the Gameobjects themselves.)
  • Pick a random entry from the Dictionary or List, use GetComponent().DoSomething(insert any params if needed) to run the method of that specific cloned GameObject.

and some illustrative code for a ‘controller’ class:

            //a list to store the scripts
            List<SomeScript> scriptList = new List<SomeScript>();

            //instantiate a copy of a prefab
            GameObject go = (GameObject)Instantiate(Resources.Load("Prefabs/MyPrefab"), launchedPanels.transform);
            //grab the script component from it
            var script1 = go.GetComponent<SomeScript>();
            //and chuck it in our list
            GameObject go2 = (GameObject)Instantiate(Resources.Load("Prefabs/MyPrefab"), launchedPanels.transform);
            var script2 = go2.GetComponent<SomeScript>();
            //repeat a third time
            GameObject go3 = (GameObject)Instantiate(Resources.Load("Prefabs/MyPrefab"), launchedPanels.transform);
            var script3 = go3.GetComponent<SomeScript>();

            //grab the first (in your case, you could write some code to pick a random element instead), and then run the DoSomething() method on it

The above is very crude - there is so much more that can be said, but ill leave it at that for simplicity. It’s really just a sample to get you thinking.

Thx. I kinda did the same you suggested. After the gameobject has been cloned I put all of them in a list. And from that I can get the specific object I want and I just use getcomponent to call the script inside.