Rerunning a script on a game object
So I have a game object called MapController which has a script called MapManager attached to it.
Map Manager basically creates an entire map and runs analysis etc on it. Now I need to this multiple times over, and unfortunately my code is a total spaghetti mess, and I'm short on time due to this being a thesis deadline. How can I have the same process run multiple times without rewriting all of my code?
I am hoping to accomplish something along these lines:
GameObject.Find ("MapController").GetComponent<MapManager> = new MapManager();
Which would hopefully rerun the Start method, even though it's a really bad way of going on about it. Could something like this work somehow? Any other alternatives which don't require me to recode everything up (I don't have enough time to do so until submission since this is already multiple months of work, and multiple changes already committed to this project).
If code is supposed to run multiple time, never put it in a Start function, but in its own (public) function. Then, you will be able to call this public function from whenever it is needed.
How about making a method that Destroy()s the script and then uses AddComponent again? Or one that Destroy()s the whole GameObject and creates a new one and adds a new script to it?
Any cleaning up you need to do could be done in OnDestroy or OnDisable in the controller
Destroying and instantiating components / gameobjects is resources consu$$anonymous$$g. Here, a simple call to his (heavy) "analysis" function will be far better.
Answer by angelx3 · Aug 09, 2016 at 08:02 AM
var mapController = GameObject.Find ("MapController");
if(mapController != null){
var mapManager = mapController.GetComponent<MapManager>();
if(mapManager ==null){
mapManager = mapController.AddComponent<MapManager>();
}
}
Your answer
Follow this Question
Related Questions
Best way to Start/Stop script during runtime. 0 Answers
Can't restart a level 2 Answers
Editing generic list through editorwindow 0 Answers
My C# Script not working 2 Answers
[SOLVED]Why does my Timer not work? (Called by button Script) 2 Answers