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

1 Answer

1

var mapController = GameObject.Find (“MapController”);
if(mapController != null){
var mapManager = mapController.GetComponent();
if(mapManager ==null){
mapManager = mapController.AddComponent();
}
}

at least their are no errors.

After reading this comment I encurage you to invest a bit into understanding how code actually works. Id est reading a c# programming book. the unity tutorials are also good, but they may not be enough. You have a misconception of defining a variable, which is absolute basic.

where are you setting "sens" in player prefs? it's reading the stored value. also, if you need it as a float then use GetFloat()/SetFloat()- there's no need to cast to another type if it's never needed as an int. if you are unsure what casting is then try your favorite search engine ;)