- Home /
Re enable the script to recover the initial variables
My Flow:
(go1.GetComponent (typeof(phase1)) as phase1).enabled = true;
(go1.GetComponent (typeof(phase1)) as phase1).enabled = false;
(go1.GetComponent (typeof(phase1)) as phase1).enabled = true;
I could not able to recover the transy intial value on re-enabling
phase1.cs
using UnityEngine; using System.Collections;
public class phase1 : MonoBehaviour {
// Use this for initialization
public Texture2D struc,activit;
public string next1, next2;
private float transy=(int)(Screen.height*1.2f),transend=(int)((float)Screen.height/1.4);
void Start () {
transy = (int)(Screen.height * 1.2f);
}
// Update is called once per frame
void OnGUI(){
Debug.Log ("I am active");
//GUI.color = Color.clear;
if (transy > transend) {
transy-=4;
}
}
}
What I want is: void Reinitialize(){ //initalize all variables again } Is there any method like this which provides for re-initializing variables
Answer by gjf · Jun 30, 2014 at 09:18 AM
from the docs:
http://docs.unity3d.com/ScriptReference/MonoBehaviour.Start.html
"Start is called on the frame when a script is enabled just before any of the Update methods is called the first time."
Answer by Kiwasi · Jun 30, 2014 at 09:16 AM
There is no reason you can't wrap your initialisation method and call it as often as you like.
void Start (){
myCustomStart();
}
void myCustomStart(){
// Run all your initialisation here
}
void OnEnable (){
myCustomStart();
}
// Inside any other method that makes sense
myCustomStart();
Is there any restriction on just calling $$anonymous$$onoBehaviour.Start() yourself?
And here's something more about using Start() in the answer to this question: How can I return back to script's "function Start()"?
I'm not saying that calling Start() again is not possible. Its just bad coding practice. At some stage later you, or another developer, will come back to the code and add something else to Start() without realising its being called from all over the place. You are setting yourself up for hours of painful debugging. Its really not worth it for the cost of writing out one method.
Yeah I agree it's bad practice given that Start() is a special Unity function (which should therefore be left to Unity to call), I was just curious whether Unity allows this. A dedicated initialisation function called from Start is certainly a better approach.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Storing my choose your own adventure questions/actions 1 Answer
Transforms are SUPER HARD! 2 Answers