- Home /
How can an object add itself to a scripts Array when it's instantiated?
I have a manager script that manages all the enemies in my scene. To do this it has an array called EnemyObject where it manages all the objects at once. How can I have the enemy add itself to the EnemyObject array when its instantiated?
Thanks Stealth
Thinking about Instantiate just makes it more complicated. Yes, you Instantiated it, but now it's a gameObject, same as any other. You just have to write code to add it to a list.
I add things to arrays all the time. Lists work too. If you just focus on "add something to a list/array" you'll find lots of examples.
Answer by asimov · Mar 12, 2015 at 09:37 PM
You need to make it a list instead of an array as this makes adding objects much easier, using .Add(). For each of the new enemies to be able to access the list, you need to make it a static variable (E.g. Inside the Manager script, when declaring the list, use public static List< GameObject> = new List ()
;) You'll need to add the System.Collections.Generic and System.Linq library headers to use Lists and Add(), respectively.
Then, in order for each new enemy to add itself to the list, you should do the work inside their Start function. Something like EnemyObjects.Add(gameObject);
This is untested but should work. Let me know how you get on.
Yes they do work but with slightly different syntax.
public var myList : List.<TYPE>; // Insert TYPE
Apparently they lists dont work in Javascript so im going to keep on using arrays. Thanks for the help anyway
Your answer
Follow this Question
Related Questions
Physics.OverlapSphere with a min radius? 1 Answer
Enemy moving sideways 1 Answer
Checking Enemies In An Area. 1 Answer
Why does my pathfinding script keep crashing Unity? 1 Answer
Javascript - find a value in an array 0 Answers