What is the proper way for making multiple instances of the same script?
So here is my situation: I am making a game where time is a factor and NPCs will move about there day based on the time. So instead of every NPC having an update function to check the time, I would like the script that calculates the time to call a function inside my NPC script every time the hour changes so that they can move to their next location. So my question is, how can I make an instance of each NPCAnimate script that is attached to each NPC, so that I can call a function from within their script? Here is what I have so far but it isn't working:
public GameObject[] npc; public NPCAnimate[] npca;
void Start () {
npc = GameObject.FindGameObjectsWithTag ("NPC");
for (int i = 0; i < npc.Length; i++) {
npca [i] = npc [i].GetComponent <NPCAnimate>();
}
}
pls halp
So you want a single script that calculates the time and then that calls a funcion in every NPC script?
Yes, I already have the time script sorted. Just need help figuring out how to reference each npc script
Answer by Penca53 · Nov 07, 2017 at 07:17 PM
You can create a List and then put all your script in it:
public class callExample : MonoBehaviour {
public GameObject[] gameObjectexample;
public List<example> exampleScriptList;
void Start () {
gameObjectexample = GameObject.FindGameObjectsWithTag ("Example");
for (int i = 0; i < gameObjectexample.Length; i++) {
exampleScriptList.Add(gameObjectexample [i].GetComponent <example>());
}
}
}
Then if you want to call a funcion in every list member:
for (int j = 0; j < gameObjectexample.Length; j++) {
exampleScriptList [j].exampleFuncion ();
}
sorry if "void Start () {" isn't in the right place... let me know if it works :)
That is actually a bad example. Since you don't interact with the array in the inspector the variables shouldn't be public. You also don't initialize the "exampleScriptList" variable. Currently you rely on the initialization through the inspector. There the user could add elements before your code runs. Also if the script would be attached dynamically the list wouldn't be initialized at all.
Finally you did not properly mark your code as code and therefore the generic parameter of the List is not visible.
I used public variables because he used public variables. I could use a [SerializeField] private variable to create a private variable but visible in the inspector for debug.
Answer by Bunny83 · Nov 07, 2017 at 07:19 PM
it isn't working
That's not a well description of your problem. Do you get an error? That means either your compiler or your runtime is already telling you what is wrong but you ask a question here and let us analyze your script from scratch....
What we can see is that you do not initialize your "npca" array. It should have the same length as your npc array.
npc = GameObject.FindGameObjectsWithTag ("NPC");
npca = new NPCAnimate[npc.Length];
// [ ... ]
Your answer
